Spring Boot 全局异常处理
SpringMvc 中对异常统一处理提供了相应处理方式,推荐大家使用的是实现接口HandlerExceptionResolver的方式,对代码侵入性较小。
在Spring Boot 应用中同样提供了对异常的全局性处理,相关注解如下:
@ControllerAdvice
该注解组合了@Component注解功能,最常用的就是作为全局异常处理的切面类,同时通过该注解可以指定包扫描的范围。@ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换
@ExceptionHandler
该注解在Spring 3.X 版本引入,在处理异常时标注在方法级别,代表当前方法处理的异常类型有哪些 具体应用以Restful 接口为例,测试保存用户接口
全局异常应用
异常抛出与全局捕捉
- UserController 查询接口
@ApiOperation(value = "根据用户id查询用户记录")
@ApiImplicitParam(name = "userId",value = "查询参数",required = true,paramType = "path")
@GetMapping("user/{userId}")
public User queryUserByUserId(@PathVariable Integer userId){
return userService.queryUserByUserId(userId);
}
- UserService 查询业务方法,抛出ParamExceptions 异常
public User queryUserByUserId(Integer userId){
AssertUtil.isTrue(true,"异常测试...");
return userMapper.queryById(userId);
}
- 全局异常处理类GlobalExceptionHandler定义
@ControllerAdvice
public class GlobalExceptionHandler{
/**
* 全局异常处理 返回json
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultInfo exceptionHandler(Exception e){
ResultInfo resultInfo=new ResultInfo();
resultInfo.setCode(300);
resultInfo.setMsg("操作失败!");
if(e instanceof ParamsException){
ParamsException pe= (ParamsException) e;
resultInfo.setMsg(pe.getMsg());
resultInfo.setCode(pe.getCode());
}
return resultInfo;
}
}
- Postman 执行测试效果
特定异常处理
通过@ExceptionHandler 标注方法可以处理特定异常,这里以用户未登录异常为例,通过全局异常进行统一处理
/**
* 用户未登录异常特殊处理 返回json
* @param authExceptions
* @return
*/
@ExceptionHandler(value = NoLoginException.class)
@ResponseBody
public ResultInfo userNotLoginHandler(NoLoginException authExceptions){
System.out.println("用户未登录异常处理。。。");
return new ResultInfo(authExceptions.getCode(),authExceptions.getMsg());
}
在用户添加接口中抛出未登录异常为例进行测试
@PutMapping("user")
@ApiOperation(value = "用户添加")
@ApiImplicitParam(name = "user",value = "用户实体类",dataType = "User")
public ResultInfo saveUser(@RequestBody User user){
if(1==1){
throw new NoLoginException();
}
ResultInfo resultInfo=new ResultInfo();
userService.saveUser(user);
return resultInfo;
}