Springboot全局异常处理无法获取message
两种处理全局异常的方法:
@ControllerAdvice
能够处理捕获Controller、Service或者Component注解下产生的异常。使用 @ExceptionHandler 注解来定义特定类型的异常处理方法。BasicErrorController
,是 Spring Boot 提供的默认错误处理器。它实现了 ErrorController 接口,用于处理 HTTP 请求中出现的异常并生成适当的错误响应。在应用部署过程中,当没有自定义的异常处理器时,BasicErrorController 会被默认使用。
异常处理范围:
- ControllerAdvice:可以用于处理应用程序中的任何异常,无论是在控制器、服务层还是其他组件中抛出的异常。可以捕获特定类型的异常,并针对每种异常类型提供自定义的处理逻辑。
- BasicErrorController:主要用于处理 HTTP 请求时发生的异常,例如请求地址不存在(404)或服务器内部错误(500)等。它通常无法处理应用程序内部的业务逻辑异常。
字面意思就是有些未被处理到的异常会默认使用BasicErrorController
。 如果在工具类中进行异常抛出,就会出现@ControllerAdvice
无法捕捉,使用BasicErrorController
返回异常的情况。
以下是代码例子:
@ControllerAdvice
@Slf4j
public class ErrorHandler {
/**
* 扑捉 BizException
* @param e
* @return
*/
@ExceptionHandler(BizException.class)
@ResponseBody
public SingleResponse handleBizException(BizException e){
log.error("错误信息1%s",e);
SingleResponse response = new SingleResponse();
response.setSuccess(false);
response.setErrCode(e.getErrCode());
response.setErrMessage(e.getMessage());
return response;
}
/**
* 扑捉 Exception
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public SingleResponse handleException(Exception e){
log.error("错误信息2%s",e);
return Response.buildError(Error.SYS_ERROR_01,e.getMessage());
}
}
@RestController
public class ErrorRestController extends BasicErrorController {
public ErrorRestController(ServerProperties serverProperties) {
super(new DefaultErrorAttributes(), serverProperties.getError());
}
@Override
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
HttpStatus status = getStatus(request);
throw new BizException(String.valueOf(status.value()), (String) body.get("message"));
}
}
如果想要通过Exception的构造器传参来处理返回的message。需要注意以下配置:
## 默认配置为never,无法获取到message信息
server.error.include-message=always