【问题标题】:Spring Boot custom error controller returning empty JSON responseSpring Boot 自定义错误控制器返回空 JSON 响应
【发布时间】:2016-08-30 07:23:31
【问题描述】:

我有一个 Spring Boot 应用程序。我已经配置了一个自定义错误控制器来处理 404 错误。它返回一个空响应。我得到了显示自定义错误控制器方法被调用的日志语句。但我在 SOAP UI 或 Chrome Postman 中没有看到响应。

 @RestController
public class MyErrorController implements ErrorController {

    private static final String PATH = "/error";

    private boolean debug = true;
    private static final Logger log = LoggerFactory.getLogger(MyErrorController.class);

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = PATH)
    public MyGlobalError error(HttpServletRequest request, HttpServletResponse response) {
        log.error("***" + RequestCorrelation.getId() + "***" + "MyErrorController - error ()");
        MyGlobalError error = new MyGlobalError(request.getMethod(), response.getStatus(),
                getErrorAttributes(request, debug));
        return error;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
    }

}

这是我的应用类

    @EnableAutoConfiguration // Sprint Boot Auto Configuration
@ComponentScan(basePackages = "com.app")
@EnableJpaRepositories("com.app.jpa") // To segregate MongoDB
                                                        // and JPA repositories.
                                                        // Otherwise not needed.
@EnableSwagger // auto generation of API docs
@SpringBootApplication
@EnableAspectJAutoProxy
@EnableConfigurationProperties

public class Application extends SpringBootServletInitializer {

    private static Class<Application> appClass = Application.class;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(appClass).properties(getProperties());

    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public FilterRegistrationBean correlationHeaderFilter() {
        FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
        filterRegBean.setFilter(new CorrelationHeaderFilter());
        filterRegBean.setUrlPatterns(Arrays.asList("/*"));

        return filterRegBean;
    }

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    static Properties getProperties() {
        Properties props = new Properties();
        props.put("spring.config.location", "classpath:/");
        return props;
    }

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter() {
            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer.favorPathExtension(false).favorParameter(true).parameterName("media-type")
                        .ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
                        .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
            }
        };
        return webMvcConfigurerAdapter;
    }

    @Bean
    public RequestMappingHandlerMapping defaultAnnotationHandlerMapping() {
        RequestMappingHandlerMapping bean = new RequestMappingHandlerMapping();
        bean.setUseSuffixPatternMatch(false);
        return bean;
    }
}

我的属性文件中有这个

#error configurations
error.whitelabel.enabled=false

这是我的日志条目

2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***-Entering: MyErrorController.error
2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***MyErrorController - error ()
2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***-Exited: MyErrorController.error

【问题讨论】:

    标签: java spring-mvc error-handling spring-boot annotations


    【解决方案1】:

    您可以使用控制器建议和单独的剩余错误处理程序来处理每种异常类型。
    see this answer

    你可以创建一个自定义响应json对象,这里需要@ResponseBody注解
    或类似此处使用的通用错误响应 click here

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 2014-12-01
      • 1970-01-01
      • 2015-09-04
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2021-02-24
      相关资源
      最近更新 更多