【问题标题】:Spring doesn't return JSON from controller for errorsSpring 不会从控制器返回 JSON 以显示错误
【发布时间】:2017-02-06 19:53:02
【问题描述】:

我已经查看了很多其他问题,但没有发现任何与我相同的问题。

我正在重构一个遗留应用程序并实现 Spring,并且我使用 web.xml 在 WebSphere 中运行 Spring 4。

我的控制器用 @ResponseBody 注释,当没有异常时它们返回 Jackson 处理的 JSON,但是如果有异常,响应的主体不是 JSON,因此,我不能很好地处理它们在我的前端 Javascript 中。

例如,如果我在需要 POST 的端点上使用 GET,我希望看到这样的 JSON:

{
  "timestamp": 1486410302434,
  "status": 405,
  "error": "Method Not Allowed",
  "exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
  "message": "Request method 'GET' not supported",
  "path": "/greeting"
}

但是我得到了这个:

Error 405: Request method 'GET' not supported

如何配置我的环境以在发生异常时返回 JSON?

这是我的网络配置:

@Configuration
@EnableWebMvc
@ComponentScan("hello")
public class WebConfig {

    @Bean
    public ViewResolver viewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();

        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        resolver.setPrefix("/Pages");
        resolver.setSuffix(".jsp");

        return resolver;
    }

还有我的 web.xml:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

【问题讨论】:

    标签: json rest spring-mvc


    【解决方案1】:

    Spring 的 HandlerExceptionResolvers 进行异常映射。 This articlethis article 描述了处理异常的多种方式的处理机制。

    您可以实现自己的 HandlerExceptionResolver 并发送回您想要的数据。

    如果你只需要一个例外,你可以使用@ControllerAdvice

    @ControllerAdvice
    class GlobalControllerExceptionHandler {
        @ResponseStatus(HttpStatus.NOT_ALLOWED)  // 405
        public void handleConflict() {
            // Return whatever JSON you need
        }
    }
    

    我不知道有一个标志可以将错误输出更改为 JSON。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      相关资源
      最近更新 更多