gpt4 book ai didi

exception-handling - 如何处理@ControllerAdvice 中所有未处理的异常?

转载 作者:行者123 更新时间:2023-12-04 07:53:09 24 4
gpt4 key购买 nike

我使用这个异常处理程序来处理我的 Spring Boot 应用程序(REST API)中的一些特定异常:

@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());
}

}

我想用一种“全局”处理方法处理所有其他异常。但是我需要在此方法中获取 HTTP 状态代码来处理错误消息等。

问题

有什么方法可以将所有未处理的异常重定向到一个特定的方法中吗?我该怎么做?

最佳答案

docs :

Any Spring bean declared in the DispatcherServlet’s application context that implements HandlerExceptionResolver will be used to intercept and process any exception raised in the MVC system and not handled by a Controller.


public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}

关于exception-handling - 如何处理@ControllerAdvice 中所有未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32646989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com