Java SpringBoot 捕获异常

java

自定义异常类 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失效,请重新登录");

以上是 Java SpringBoot 捕获异常 的全部内容, 来源链接: utcz.com/z/394555.html

回到顶部