Spring Boot 全局异常处理

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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值