我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理

创建统一异常处理器

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //添加一个注解 ExceptionHandler
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error().message("执行了全局异常");
    }
    //自定义异常
    @ExceptionHandler({OnlineException.class})
    @ResponseBody
    public R error(OnlineException e){
        log.error(e.getMessage());
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }
}

测试

统一异常处理

自定义异常

创建自定义异常类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class OnlineException extends RuntimeException {
    @ApiModelProperty(value = "状态码")
    private Integer code;
    private String msg;
    
}

业务中需要的位置抛出OnlineException

try {
    int a = 10/0;
}catch(Exception e) {
    throw new OnlineException(20001,"出现自定义异常");
}

添加异常处理方法

OnlineExceptionHandler.java中添加

@ExceptionHandler(OnlineException.class)
@ResponseBody
public R error(OnlineException e){
    e.printStackTrace();
    return R.error().message(e.getMsg()).code(e.getCode());
}

相关文章:

  • 2021-05-21
  • 2021-10-10
  • 2021-10-09
  • 2021-04-13
  • 2021-08-18
  • 2021-10-29
  • 2021-12-29
  • 2021-06-08
猜你喜欢
  • 2021-07-15
相关资源
相似解决方案