当前位置: 首页 > 知识库问答 >
问题:

@ExceptionHandler@EnableWebMvc,则返回响应实体的 HttpMediaType 不可接受的异常 (406)

顾喜
2023-03-14

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

我想使用@ControlllerAdVP来处理控制器引发的异常。

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

如果我取消对下面的@EnableWebMvc的注释,响应实体能够正确返回JSON结果,但是,@Controlller建议将无法捕获异常。

@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中返回字符串,而@ControlllerAdvie也能够捕获和处理异常。

这是我的控制器建议:

@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.html" target="_blank">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工作,因为我真的想返回一个响应实体类型,并且它引发的异常可以被@ControllerAdvice捕获。欢迎任何建议。

提前谢谢。

共有3个答案

万俟浩
2023-03-14
  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);
                            }
                        }
    
                        <dependency>
                                    <groupId>org.springframework.boot</groupId>
                                    <artifactId>spring-boot-starter-hateoas</artifactId>
                                </dependency>
    
            @Configuration
            @EnableWebMvc
            public class WebConfig extends WebMvcConfigurerAdapter {
    
    
            }
    

龙涵蓄
2023-03-14

找到了罪魁祸首,在评论了下面的代码后,一切都像一个魔咒。无论如何,谢谢大家!

public HandlerExceptionResolver handlerExceptionResolver()
{
    return new HandlerExceptionResolver()
    {
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
        {
            return null;
        }
    };
}
皮嘉德
2023-03-14

使用@RestController,

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

- 确保您的请求映射工作并记录一些东西。

-尝试为@RestController使用@RestControlllerAdvie

 类似资料:
  • 我正在使用@ExceptionHandler来管理我的所有异常,并为任何抛出异常的REST API返回一个JSON响应。目前我管理两个异常,第一个是ResourceNotFoundException,它可以工作,但第二个是FileExtensionException,它不工作。它在eclipse控制台中抛出这个异常,而在rest响应中抛出任何东西。 2015-09-21 09:09:05.197错

  • 使用Guzzle,我正在使用JSON格式的一些外部API,通常我获取数据 $data = $request- 但是我无法从这个不同的api中获取数据。数据似乎没有出现在“响应体”中。 这个api调用有效:https://i.ibb.co/80Yk6dx/Screenshot-2.png 这不起作用:https://i.ibb.co/C239ghy/Screenshot-3.png

  • 当我从RestController返回POJO时,它在JSON对象中转换。但是当我尝试返回controller返回纯文本。怎么了? 我的RestController:

  • 我使用的是Spring版本4(Spring data),我想将Object作为JSON返回,我想知道以下代码即使不使用xmlRootElement注释用户类也能工作: 任何机构都可以解释吗?当我需要注释要返回为JSON的对象类时,响应体/响应实体是否自己完成工作?

  • 这方面的最佳实践是什么。NET与Web API?特别是WebRESTAPI。当异常发生时,RESTAPI是否应该在响应体中返回异常? 当然,我会返回500或类似的HTTP状态。但是当我用这个错误代码响应时,最佳实践是什么?或者更好的是,规范或RESTAPI对此有何规定? 返回异常(我所做的)

  • 应用程序是使用Spring MVC 4、Hibernate和jQuery开发的 下面jquery AJAX调用没有给出正确的响应。。说明406错误(不可接受) 我知道这是一个非常古老而常见的问题。我尝试过: 杰克逊罐子 在请求映射注释中:生产者作为JSON 在请求映射注释中:标头为JSON 2和3的组合 $. post而不是$. ajax(我知道这没什么区别) 我的bean对象(Validatio