Exception handling 如何处理@ControllerAdvice中所有未处理的异常?
我使用此异常处理程序来处理Spring引导应用程序(REST API)中的一些特定异常: 我想用一种“全局”处理方法来处理所有其他异常。但是我需要在这个方法中获取HTTP状态代码来处理错误消息等 问题 有没有办法将所有未处理的异常重定向到一个特定的方法?我该怎么做?请参阅: DispatcherServlet应用程序中声明的任何Springbean 实现HandlerExceptionResolver的上下文将用于 拦截并处理MVC系统中引发的任何异常,而不是 由控制器控制Exception handling 如何处理@ControllerAdvice中所有未处理的异常?,exception-handling,spring-boot,Exception Handling,Spring Boot,我使用此异常处理程序来处理Spring引导应用程序(REST API)中的一些特定异常: 我想用一种“全局”处理方法来处理所有其他异常。但是我需要在这个方法中获取HTTP状态代码来处理错误消息等 问题 有没有办法将所有未处理的异常重定向到一个特定的方法?我该怎么做?请参阅: DispatcherServlet应用程序中声明的任何Springbean 实现HandlerExceptionResolver的上下文将用于 拦截并处理MVC系统中引发的任何异常,而不是 由控制器控制 我读了这篇文章,但我
我读了这篇文章,但我不需要
model和view
,应该通过@ResponseBody
返回我的ResponseMessage
。添加一个处理异常的方法。将为错误处理选择最具体的。。。只需添加HttpServletRequest
和/或HttpServletResponse
作为方法参数。
@ControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public
@ResponseBody
ResponseMessage notFound(NotFoundException ex) {
return new NotFoundResponseMessage(ex.getMessage());
}
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public
@ResponseBody
ResponseMessage unsupportedMediaType(HttpMediaTypeNotSupportedException ex) {
return new UnsupportedMediaTypeResponseMessage(ex.getMessage());
}
@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public
@ResponseBody
ResponseMessage unauthorized(UnauthorizedException ex) {
return new UnauthorizedResponseMessage(ex.getMessage());
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public
@ResponseBody
ResponseMessage methodNotAllowed(HttpRequestMethodNotSupportedException ex) {
return new MethodNotAllowedResponseMessage(ex.getMessage());
}
@ExceptionHandler(ForbiddenException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public
@ResponseBody
ResponseMessage forbidden(ForbiddenException ex) {
return new ForbiddenResponseMessage(ex.getMessage());
}
}
public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}