Java SpringBoot 捕获异常
Java SpringBoot 捕获异常
自定义异常类 JwtExceptionUtils
@Data
public class JwtExceptionUtils extends RuntimeException {
private EnumDeclare.Code code;
public JwtExceptionUtils(EnumDeclare.Code code, String message) {
super(message);
this.code = code;
}
}
捕捉类 GlobalExceptionHandler
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
/**
* 全局异常捕获, 处理登录失败或token失效异常
*
* @return
*/
@ExceptionHandler(value = JwtExceptionUtils.class)
public ResultDto handler(JwtExceptionUtils e) {
return new ResultDto(e.getCode(), e.getMessage());
}
/**
* 全局异常捕获
*
* @return
*/
@ExceptionHandler(value = RuntimeException.class)
public ResultDto handler2(Exception e) {
return new ResultDto(EnumDeclare.Code.EXCEPTION, e.getMessage());
}
}
抛出异常
throw new JwtExceptionUtils(EnumDeclare.Code.UNAUTHORIZED, "token失效,请重新登录");
如有疑问欢迎留言沟通交流 彦桢博客