我已经制作了一个小型的Spring Boot应用程序,现在我正在尝试添加自己的异常处理。我遇到了一个问题,即使该应用程序按预期运行,我仍然在日志中出现错误。配置:
异常处理程序如下所示:
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundException.class)
@ResponseBody ErrorInfo handleNotFoundRequest(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL().toString(), ex);
}
}
我的 Controller 抛出异常:
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = {"application/json"})
public @ResponseBody
HashMap environment(@PathVariable("id") long id) {
HashMap<String, Object> map = new HashMap();
Environment env = environmentService.getEnvironment(id);
if(env == null) throw new NotFoundException("Environment not found: " + id);
map.put("environment", env);
return map;
}
我的Spring Boot应用程序设置:
@SpringBootApplication
@EnableAutoConfiguration(exclude=ErrorMvcAutoConfiguration.class)
@ComponentScan
public class QaApiApplication {
public static void main(String[] args) {
SpringApplication.run(QaApiApplication.class, args);
}
}
ServletInitializer:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(QaApiApplication.class);
}
}
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
......
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果我执行生成异常的调用,则会得到正确的响应,即带有预期JSON的404。但是,我在日志中看到ErrorPageFilter错误:
就启动/部署而言,没有错误,据我所知一切似乎都在工作。我怀疑有些默认行为没有被正确覆盖,但是我还没有弄清楚到底是什么。
对此的任何帮助/提示都将不胜感激,因为我对问题的根源有所了解。
最佳答案
如果您仍然使用Spring-boot版本1.2.3(而不是1.4.2.RELEASE,其中solution provided),则扩展SpringBootServletInitializer
并重写方法run
,如下所示:
@SpringBootApplication
@EnableAutoConfiguration(exclude=ErrorMvcAutoConfiguration.class)
@ComponentScan
public class QaApiApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(QaApiApplication.class, args);
}
@Override
protected WebApplicationContext run(SpringApplication application) {
application.getSources().remove(ErrorPageFilter.class);
return super.run(application);
}
}
这个对我有用。