SpringBoot全局异常与数据校验

利用idea 工具,很容易的搭建一个SpringBoot项目,要引入的maven依赖如下:


    org.springframework.boot
    spring-boot-starter-validation


    org.springframework.boot
    spring-boot-starter-web



    org.springframework.boot
    spring-boot-starter-test
    test

定义成功失败 返回码

public class Code {

    /**
     * 成功
     */
    public static int SUCCESSED = 1;
    /**
     * 失败
     */
    public static int FAILED = -1;
}

定义接口返回响应实体

public class Response implements Serializable{

   /**
    * 
    */
   private static final long serialVersionUID = 4250719891313555820L;
   /**
    * 返回结果集
    */
   private T result;
   /**
    * 返回消息
    */
   private String msg;
   /**
    * 响应码
    */
   private Integer code;
   //set get 略
}

全局异常拦截和验证

定义自定义业务异常

public class MyException extends RuntimeException {

    private static final long serialVersionUID = -5875371379845226068L;


    public MyException(){}

    public MyException(String msg){
        this.msg = msg ;
    }

    /**
     * 异常信息
     */
    private String msg ;

    /**
     * 具体异常码
     */
    private int code = Code.FAILED;
   get set 略 

编写全局异常控制器并对自定义异常做处理

@ControllerAdvice
public class GlobalExceptionHandler {
     private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = MyException.class)
@ResponseBody
public Response myExceptionErrorHandler(MyException ex) throws Exception {
    logger.error("myExceptionErrorHandler info:{}",ex.getMessage());
    Response r = new Response<>();
    r.setMsg(ex.getMsg());
    r.setCode(ex.getCode());
    return r;
}

编写controller模拟抛出业务异常

@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping(value = "/update")
Response update(User user){

    //todo 此处为模拟异常抛出
    if(true){
        throw new MyException("更新失败");
    }
    //todo 此处为模拟返回
    Response response = new Response<>();
    response.setCode(Code.SUCCESSED);
    response.setResult(true);
    return  response;
}

}

postMan模拟请求接口,进行验证
SpringBoot全局异常与数据校验_第1张图片
数据绑定异常处理
通常我们操作数据的时候,不仅前端需要进行数据校验,后端也应当进行拦截和进行相应的错误提示,
JSR-303校验框架也是我们的一种选择。
编写实体User,并对属性进行注解控制

public class User {

    @NotNull(message = "用户名不能为空")
    private String userName;

    private  int age;
   //...

全局异常控制类加入拦截

@ControllerAdvice
public class GlobalExceptionHandler {
     private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

     @ExceptionHandler(value = BindException.class)
     @ResponseBody
     public Response bindExceptionErrorHandler(BindException ex) throws Exception {
          logger.error("bindExceptionErrorHandler info:{}",ex.getMessage());
          Response r = new Response<>();
          StringBuilder sb = new StringBuilder();
          FieldError fieldError = ex.getFieldError();
          sb.append(fieldError.getDefaultMessage());
          r.setMsg(sb.toString());
          r.setCode(Code.FAILED);
          return r;
     }
  //...

编写控制器

@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping(value = "/add")
    Response add(@Validated User user){

        //todo 此处为模拟返回
        Response response = new Response<>();
        response.setCode(Code.SUCCESSED);
        response.setResult(new User());
        return  response;
    }
  //...

postMan模拟请求

不填写任何属性,模拟添加操作,准确进行拦截和报错
SpringBoot全局异常与数据校验_第2张图片

代码地址:https://github.com/pengziliu/spring-boot-2.0-leaning
项目结构预览:
SpringBoot全局异常与数据校验_第3张图片

你可能感兴趣的:(Springboot)