springboot 自定义异常
Posted 小污龟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 自定义异常相关的知识,希望对你有一定的参考价值。
生名一个异常类:
比如用户登录授权异常类:
/** * 自定义业务异常对象 */ public class AuthorizationException extends RuntimeException { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = 1L; private int code; private Object data; /* * 默认异常 */ public AuthorizationException() { this(200,"请求成功"); } public AuthorizationException(int code, String msg) { super(msg); this.code = code; } public AuthorizationException(int code, String msg, Object data) { super(msg); this.code = code; this.data = data; } public AuthorizationException(String message) { super(message); code = 420; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
声明一个全局异常处理类:RestControllerAdvice.java
/** * 全局异常处理类,处理系统内所有异常,并给客户端相关的响应. */ @ControllerAdvice public class RestControllerAdvice { private static final Logger logger = LoggerFactory.getLogger(RestControllerAdvice.class); @ExceptionHandler(AuthorizationException.class) @ResponseBody public JsonResponse<?> handleBusinessException(AuthorizationException ex, HttpServletResponse response) { logger.error(ex.getMessage(),ex); return new JsonResponse<>(ex.getCode(),ex.getMessage(), ex.getData()); } }
JsonResponse.java
@Data public class JsonResponse<T> { Integer code; String message; T data; public JsonResponse(Integer code, String message) { this.code = code; this.message = message; } public JsonResponse(Integer code, T data) { this.code = code; this.data = data; } public JsonResponse(Integer code, String message, T data) { this.code = code; this.message = message; this.data = data; } }
在业务层抛出 刚才声明的AuthorizationException异常:
@RequestMapping("/test")
public Boolean test(){throw new AuthorizationException(401, "未登录"); }
这样就完成啦
以上是关于springboot 自定义异常的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot 异常自定义处理 - 意外的 HTTP 状态
Springboot+自定义注解+自定义AOP前置增强+自定义异常+自定义异常捕获