在过滤器Filter中抛出一个全局异常可以捕获的异常
程序员文章站
2022-06-21 13:43:58
1、创建自定义异常package com.manager.exception;import com.manager.enums.ExceptionEnum;public class TokenException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; private Integer errCode; privat......
1、创建自定义异常
public class TokenException extends RuntimeException { private static final long serialVersionUID = 1L; private Integer errCode; private String message; public TokenException(Integer errCode){ this.errCode = errCode; this.message = ExceptionEnum.getMessage(errCode); } public TokenException(String message){ this.errCode = ExceptionEnum.TOKEN.getCode(); this.message = message; } public TokenException(int errCode, String message) { this.errCode = errCode; this.message = message; } public TokenException(ExceptionEnum exceptionEnum) { this.errCode = exceptionEnum.getCode(); this.message = exceptionEnum.getMessage(); } public TokenException(ExceptionEnum exceptionEnum, String message) { this.errCode = exceptionEnum.getCode(); this.message = message; } public int getCode() { return errCode; } public void setCode(int errCode) { this.errCode = errCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2、在过滤器中注入HandlerExceptionResolver
@Autowired @Qualifier("handlerExceptionResolver") private HandlerExceptionResolver resolver;
3.使用
if(StringUtils.isEmpty(redisToken)){ resolver.resolveException(request, response, null, new TokenException(ExceptionEnum.TOKEN)); return; }
4、全局异常捕获
@Slf4j @ResponseBody @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler({TokenException.class}) public Map<String,Object> TokenException(TokenException e) { log.error("捕获业务异常:", e); Map<String,Object> map = new HashMap<String,Object>(2); map.put("code",e.getCode()); map.put("msg",e.getMessage()); return map; }
}
本文地址:https://blog.csdn.net/qq_38377774/article/details/107696206