由于我想控制应用程序的所有端点的输出,包括未明确定义的端点,我创建了一个看起来像这样的简单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
。此外 - 这是处理不存在资源的可接受方式吗?