简体   繁体   English

Springboot异常处理程序没有捕获异常

[英]Springboot exception handler doesn't catch exception

In Spring boot and rest application, i have configured a exception handler as following. 在Spring Boot and Rest应用程序中,我已按如下方式配置了异常处理程序。 It works fine if an exception is thrown after request makes it to rest service. 如果在请求使其停止服务后引发异常,则该方法工作正常。

The Rest api expects Content-Type of "application/json" and If I do not send that content-type header to the api, exception handler does not catch the exception. Rest api期望Content-Type为“ application / json”,并且如果我不将该内容标头发送到api,则异常处理程序将无法捕获该异常。 It prints following information in the log: 它在日志中打印以下信息:

DEBUG [o.s.w.s.DispatcherServlet] DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/app/v1.0/customers/customer/zones/zoneName.]
DEBUG [o.s.w.s.m.m.a.RequestMappingHandlerMapping] Looking up handler method for path /app/v1.0/customers/customer/zones/zoneName.
DEBUG [o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver] Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain' not supported
DEBUG [o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver] Invoking @ExceptionHandler method: public final org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)
DEBUG [o.s.w.s.DispatcherServlet] Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG [o.s.w.s.DispatcherServlet] Successfully completed request

Here's the exception handler class: 这是异常处理程序类:

@ControllerAdvice
@RestController  
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler
{

    @ExceptionHandler(Exception.class)  
    public final ResponseEntity<java.lang.Object> handleException(Throwable ex,WebRequest req)
    {
        ErrorResponse errorResponse = null;
        if (ex instanceof ApiException)
        {
            errorResponse = new ErrorResponse((ApiException) ex);
        }
        else
        {
            logger.error(ex);
            errorResponse = new ErrorResponse();
            errorResponse.setCode(HttpCodes.HTTP_CODE_500);
            errorResponse.setError(ex.getMessage());
        }
        return new ResponseEntity<Object>(errorResponse,
                HttpStatus.valueOf(errorResponse.getCode()));

    }
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request)
    {
        Map<String, String> responseBody = new HashMap<String, String>();
        responseBody.put("path", request.getContextPath());
        responseBody.put("message",
                "The URL you have reached is not in service at this time (404).");
        return new ResponseEntity<Object>(responseBody, HttpStatus.NOT_FOUND);
    }
}

Your class will only catch errors raised from within a controller. 您的课程将仅捕获从控制器内部引发的错误。 The error you are seeing occurs before a controller is invoked, as Spring cannot find a controller to handle the request. 您看到的错误发生在调用控制器之前,因为Spring无法找到控制器来处理请求。

DEBUG [o.s.w.s.m.m.a.RequestMappingHandlerMapping] Looking up handler method for path /app/v1.0/customers/customer/zones/zoneName.
DEBUG [o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver] Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain' not supported

Notice the handler is null. 请注意,处理程序为null。

You will also need to implement a HandlerExceptionResolver to handle that type of exception: http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers 您还需要实现HandlerExceptionResolver来处理这种类型的异常: http : HandlerExceptionResolver

See Spring exception handler outside controller for more details. 有关更多详细信息,请参见控制器外部的Spring异常处理程序

Here's final solution: 这是最终的解决方案:

@ControllerAdvice  
public class SpringExceptionHandler extends ExceptionHandlerExceptionResolver
{
    @ExceptionHandler(org.springframework.web.HttpMediaTypeNotSupportedException.class)
    public ResponseEntity<Object> handleControllerException(HttpMediaTypeNotSupportedException ex, WebRequest req)
    {
        ErrorResponse errorResponse = null;
        ex.printStackTrace();
        errorResponse = new ErrorResponse();
        errorResponse.setCode(HttpCodes.HTTP_CODE_INTERNAL_ERROR);
        errorResponse.setError(ex.getMessage());
        return new ResponseEntity<Object>(errorResponse,
            HttpStatus.valueOf(errorResponse.getCode()));
    }
}

Now I need to make some changes to make it work for all exceptions including controller thrown but that is for later. 现在,我需要进行一些更改,以使其适用于所有异常,包括引发的控制器,但这将在以后提供。 (Thanks Adam). (感谢亚当)。

Important note: if there's both a global handler and an entity handler, spring ignores global handler. 重要说明:如果同时存在全局处理程序和实体处理程序,spring将忽略全局处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM