重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

SpringBoot中如何实现全局异常与数据校验

SpringBoot中如何实现全局异常与数据校验,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

创新互联公司是一家专注于成都网站制作、成都网站设计与策划设计,冷水江网站建设哪家好?创新互联公司做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:冷水江等地区。冷水江做网站价格咨询:18982081108

项目建立

利用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  

很简单,除了加入web功能还加入了我们需要用到的JSR-303校验框架。

定义成功失败 返回码

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中如何实现全局异常与数据校验

数据绑定异常处理

通常我们操作数据的时候,不仅前端需要进行数据校验,后端也应当进行拦截和进行相应的错误提示,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中如何实现全局异常与数据校验

项目结构预览:

SpringBoot中如何实现全局异常与数据校验

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。


分享题目:SpringBoot中如何实现全局异常与数据校验
分享网址:http://cqcxhl.cn/article/pgpdjh.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP