如何让一个由ControllerAdvice注释的类来处理不同类型的异常?

Dan*_*own 5 java spring exception spring-mvc internal-server-error

我有一个叫做GlobalExceptionHandler注释的类ControllerAdvice.它妥善处理所有NoHandlerFoundExceptions.我添加了一个新方法来处理InternalError异常,但它不处理这些异常; 因此,我仍在接受HTTP Status 500.

基于此链接的异常类 500 (Internal Server Error)ConversionNotSupportedException.

我尝试了以下代码但没有捕获内部服务器错误.

1

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleExceptionNotFound(NoHandlerFoundException ex) {
        System.err.println("not found");
        return "redirect:/error";
    }

    @ExceptionHandler(ConversionNotSupportedException.class)
//  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleExceptionsInternalError(ConversionNotSupportedException ex) {
        ex.printStackTrace();
        System.err.println("internal error");
        return "redirect:/error";
    }

}
Run Code Online (Sandbox Code Playgroud)

2

@ExceptionHandler(ConversionNotSupportedException.class)
public String handleExceptionsInternalError(HttpServletRequest req, ConversionNotSupportedException ex) {
Run Code Online (Sandbox Code Playgroud)

3

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleExceptionsInternalError(ConversionNotSupportedException ex) {
Run Code Online (Sandbox Code Playgroud)

我需要处理的例外情况如下:

HTTP Status 500 - Could not resolve view with name 'user' in servlet with name 'myproject'
javax.servlet.ServletException: Could not resolve view with name 'user' in servlet with name 'myproject'
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1211)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1011)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Run Code Online (Sandbox Code Playgroud)

Dan*_*own 2

控制器建议似乎无法处理此类异常。我向我添加了以下代码web.xml来处理此异常。如果您有更好的解决方案请告诉我。谢谢。

<error-page>
    <error-code>500</error-code>
    <location>/errorhandler</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)