从零开始的SpringBoot项目 ( 七 ) 统一返回结果集Result 和 异常处理

import java.io.Serializable;
import lombok.Data;
import org.springframework.http.HttpStatus;

@Data
public class Result implements Serializable {

    private static final long serialVersionUID = -1802122468331526708L;

    private Integer code;// 状态码
    private String msg;// 返回信息
    private Object data;// 返回数据


    //自定义code,msg,data
    private Result(Integer code, String msg, Object data) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    //自定义data
    private Result(Object data) {
        this.data = data;
        this.code = HttpStatus.OK.value();
        this.msg = HttpStatus.OK.getReasonPhrase();
    }

    //自定义code,msg
    private Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private Result() {
        this.code = HttpStatus.OK.value();
        this.msg = HttpStatus.OK.getReasonPhrase();
    }

    public static Result success(Integer code, String msg, Object data) {
        return new Result(code, msg, data);
    }

    public static Result success(Integer code, String msg) {
        return new Result(code, msg);
    }

    public static Result error(Integer code, String msg) {
        return new Result(code, msg);
    }

    public static Result success(Object data) {
        return new Result(data);
    }

    public static Result success() {
        return new Result();
    }

}

Controller 层使用 Result

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my_springboot.user.pojo.UserInfoDO;
import com.my_springboot.user.service.IUserInfoService;
import com.my_springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户信息前端控制器
 * </p>
 *
 * @author JiHC
 * @since 2020-08-21
 */
@RestController
@RequestMapping("/user")
@Api(value = "UserInfoController", tags = {"用户模块"})
public class UserInfoController {

    @Autowired
    IUserInfoService userInfoService;

    @ApiOperation("新增用户信息")
    @PostMapping(value = "/saveUser")
    public Result saveUser(@RequestBody UserInfoDO userInfoDO) {
        userInfoService.save(userInfoDO);
        return Result.success(HttpStatus.CREATED.value(), HttpStatus.CREATED.getReasonPhrase());
    }

    @ApiOperation("根据问题id修改问题")
    @PutMapping(value = "/updateUser")
    public Result updateUser(@RequestBody UserInfoDO userInfoDO) {
        String id = userInfoDO.getId();
        if (null == id || "".equals(id)) {// 无内容
            return Result
                    .error(HttpStatus.NO_CONTENT.value(), HttpStatus.NO_CONTENT.getReasonPhrase());
        }
        if (null==userInfoService.getById(id)) {// 未找到
            return Result
                    .error(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        userInfoService.updateById(userInfoDO);
        return Result.success();
    }

    @ApiOperation("根据id删除用户信息")
    @DeleteMapping(value = "/removeUser")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "string", required = true, paramType = "query")
    public Result removeUser(@RequestParam String id) {
        if (null == id || "".equals(id)) {// 无内容
            return Result
                    .error(HttpStatus.NO_CONTENT.value(), HttpStatus.NO_CONTENT.getReasonPhrase());
        }
        if (null==userInfoService.getById(id)) {// 未找到
            return Result
                    .error(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        userInfoService.removeById(id);
        return Result.success();
    }

    @ApiOperation("信息")
    @PostMapping(value = "/listUserPage")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码", dataType = "int", required = true, paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "int", required = true, paramType = "query", defaultValue = "10")
    })
    public Result listUserPage(Integer pageNum, Integer pageSize) {
        Page<UserInfoDO> page = userInfoService.listUserPage(new Page(pageNum, pageSize));
        return Result.success(page);
    }
}

启动项目访问接口 访问修改接口 , 输入不存在的id , 期望返回404

 成功!

统一异常处理 : 

未添加异常处理时 , 参数错误的响应体 : 

 

 添加 控制器的异常处理类 ErrorHandler

import com.my_springboot.util.Result;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 *  控制器的异常处理类
 */
@ControllerAdvice
public class ErrorHandler {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ErrorHandler.class);

    /**
     * 输入参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Result> NotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.debug("异常详情 ", e);
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors() == false) {
            return null;
        }
        Map<String, String> fieldErrors = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getCode() + "|" + error.getDefaultMessage());
        }
        return new ResponseEntity<>(Result.error(422, "输入错误", fieldErrors),
                HttpStatus.UNPROCESSABLE_ENTITY);
    }

    /**
     * 404异常处理
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<Result> NoHandlerFoundExceptionHandler(Exception e) {
        log.debug("异常详情:", e);
        return new ResponseEntity<>(Result.error(404, "页面丢失了!"), HttpStatus.NOT_FOUND);
    }

    /**
     * 默认异常处理,前面未处理
     */
    @ExceptionHandler(value = Throwable.class)
    public ResponseEntity<Result> defaultHandler(Exception e) {
        log.debug("异常详情:", e);
        return new ResponseEntity<>(Result.error(500, "服务器错误:" + e),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

重启项目 , 访问 Swagger , 参数错误的响应体 : 

 

 配置成功 !

 

posted on 2020-08-21 17:17  法哈席基  阅读(2457)  评论(0编辑  收藏  举报