ErrorPageFilter与ResponseEntityExceptionHandler冲突

时间:2015-05-26 13:09:50

标签: java spring spring-mvc spring-boot

由于我想控制应用程序的所有端点的输出,包括未明确定义的端点,我创建了一个看起来像这样的简单DefaultController

@RestController
public class DefaultController {

    @RequestMapping("/**")
    public void unmappedRequest(HttpServletRequest request) {
        throw new ResourceNotFoundException();
    }
}

我还有一个@ControllerAdvice错误控制器,它扩展了ResponseEntityExceptionHandler并覆盖了该类的所有方法,特别是

@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
    if(HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
        request.setAttribute("javax.servlet.error.exception", ex, 0);
    }

    SearchOutput output = new SearchOutput(body);
    return new ResponseEntity<>(output, headers, status);
}

我还添加了一个方法来处理默认映射器抛出的ResourceNotFoundException

@ExceptionHandler(ResourceNotFoundException.class)
public @ResponseBody ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request) {
    HttpHeaders headers = new HttpHeaders();
    HttpStatus status = HttpStatus.NOT_FOUND;

    ErrorOutput out = new ErrorOutput("Resource not found", status);
    return this.handleExceptionInternal(ex, out, headers, status, request);
}

我声明error.whitelabel.enabled:false并将exclude={ErrorMvcAutoConfiguration.class}添加到@EnableAutoConfiguration注释中,并且在独立的Tomcat容器中运行此应用程序时仍有两个问题:

  • ErrorPageFilter抱怨每次Cannot forward to error page for request [/something/not/existing] as the response has already been committed被抛出时ResourceNotFoundException这个事实;
  • 当浏览器(自动)请求favicon.ico时,会记录Failed to invoke @ExceptionHandler method方法的handleExceptionInternal错误,其中包含说明Could not find acceptable representation

此外 - 这是处理不存在资源的可接受方式吗?

0 个答案:

没有答案