@ExceptionHandler无法与@EnableWebMvc配合使用,为ResponseEntity

时间:2018-08-24 09:27:33

标签: java spring spring-mvc spring-boot

我在Spring Boot(版本1.5.13)中有一些REST Web服务

我想使用@ControllerAdvice处理控制器抛出的异常。

对于下面的API testA,如果id = 123,则@ControllerAdvice类能够捕获并处理异常,但是,如果id不等于123,则我的程序无法将ResponseEntity转换为JSON和“ org .springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示形式(406)”。

如果我取消注释下面的@EnableWebMvc,则ResponseEntity能够正确返回JSON结果,但是,@ControllerAdvice将无法捕获异常。

@RestController("SpocController")
//@EnableWebMvc
@RequestMapping(value = { "/testing" })
public class TestController 
{   
    @GetMapping(value = "/testA", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<Object> testA(@RequestParam String id) throws IOException   
    {       
        if(id.equals("123"))
        {
            throw new IOException("customized exception");
        }

        Map<String,Object> body = new HashMap<String, Object>();
        body.put("hello", "hihi");

        return new ResponseEntity<Object>(body, HttpStatus.OK);     
    }

    @GetMapping(value = "/testB", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String testB(@RequestParam String id) throws IOException 
    {
        if(id.equals("123"))
        {
            throw new IOException("customized exception");
        }

        return "{ \"ok\":\"test ok\" }";
    }
}

对于API testB,由于返回类型为String,因此它能够以JSON返回字符串,而@ControllerAdvice也能够捕获和处理异常。

这是我的ControllerAdvice:

@ControllerAdvice
public class TestExceptionHandler
{
    @ResponseBody
    @ExceptionHandler(IOException.class)
    protected ResponseEntity<Object> handleIOException(IOException ex) 
    {   
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("message", ex.getMessage());        

        return new ResponseEntity(map, HttpStatus.INTERNAL_SERVER_ERROR);       
    }   
}

这是我上面提到的HttpMediaTypeNotAcceptableException(406)。

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:259)
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:208)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:113)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

1)无论我将@EnableWebMvc放在何处(在@ RestController,@ ControllerAdvice或其他类中),我的@ExceptionHandler都将无法捕获任何异常。知道为什么会发生吗?

2)我想使我的API testA正常工作,因为我真的想返回ResponseEntity类型,并且@ControllerAdvice可以捕获它引发的异常。欢迎任何建议。

谢谢。

3 个答案:

答案 0 :(得分:0)

使用@RestController

无需使用@ResponseBody,您可以查看文档以了解更多详细信息。

-确保您的请求映射正常工作并记录一些内容。

-尝试对@RestController使用@RestControllerAdvice

答案 1 :(得分:0)

  1.                     @RestController
                        @RequestMapping(value = { "/testing" })
                        public class ExceptionController {
                             @GetMapping(value = "/testA", produces = MediaType.APPLICATION_JSON_VALUE)
                                public  ResponseEntity<Object> testA(@RequestParam String id) throws IOException   
                                {       
                                    if(id.equals("123"))
                                    {
                                        throw new IOException("customized exception");
                                    }
    
                                    Map<String,Object> body = new HashMap<String, Object>();
                                    body.put("hello", "hihi");
    
                                    return new ResponseEntity<Object>(body, HttpStatus.OK);     
                                }
                             @GetMapping(value = "/testB", produces = MediaType.APPLICATION_JSON_VALUE)
                                public  String testB(@RequestParam String id) throws IOException 
                                {
                                    if(id.equals("123"))
                                    {
                                        throw new IOException("customized exception");
                                    }
    
                                    return "{ \"ok\":\"test ok\" }";
                                }
    
                        }
    
    

2。更改您的建议控制器-:

                    package com.ad.blog.controller;

                    import java.io.IOException;
                    import java.util.Optional;

                    import org.springframework.hateoas.VndErrors;
                    import org.springframework.http.HttpStatus;
                    import org.springframework.http.ResponseEntity;
                    import org.springframework.web.bind.annotation.ExceptionHandler;
                    import org.springframework.web.bind.annotation.RequestMapping;

                    @org.springframework.web.bind.annotation.ControllerAdvice
                    @RequestMapping(produces = "application/vnd.error+json")
                    public class ControllerAdvice {
                        @ExceptionHandler(IOException.class) public ResponseEntity < VndErrors > notFoundException(final IOException e) {
                            return error(e, HttpStatus.NOT_FOUND, e.getMessage());
                        }
                        private ResponseEntity < VndErrors > error(final Exception exception, final HttpStatus httpStatus, final String logRef) {
                            final String message = Optional.of(exception.getMessage()).orElse(exception.getClass().getSimpleName());
                            return new ResponseEntity < > (new VndErrors(logRef, message), httpStatus);
                        }
                    }
  1. 您需要在pom.xml文件中添加hateos依赖项。
                    <dependency>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-hateoas</artifactId>
                            </dependency>
  1. @EnableWebMVc批注用于启用覆盖DispatcherServlet默认配置的MVC Java配置。如果要覆盖默认配置,则创建一个class-:
        @Configuration
        @EnableWebMvc
        public class WebConfig extends WebMvcConfigurerAdapter {


        }

答案 2 :(得分:0)

找到了罪魁祸首,在注释了以下代码部分之后,所有内容都像一个魅力。无论如何,谢谢大家!

public HandlerExceptionResolver handlerExceptionResolver()
{
    return new HandlerExceptionResolver()
    {
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
        {
            return null;
        }
    };
}