【发布时间】:2016-12-20 12:48:00
【问题描述】:
我在 spring mvc 应用程序中构建了以下小错误处理程序:
@ControllerAdvice
public class Error Handler{
@ExceptionHandler(value={Throwable.class})
public ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Throwable t){
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
// ... some more stuff and output
}
}
我现在的问题是,基于 spring 的错误处理没有正确设置 HTTP 错误代码。我的第一次尝试是基于web.xml 的解决方案:
- positiv:正确设置 HTTP 状态代码
- 否定:只处理我提供的错误代码
我的新解决方案(见上文)更适合我的目的。但是我现在必须找到一个解决方案才能设置 http 状态代码。
我仔细查看了Throwable,似乎它在正确的情况下提供了正确的错误:
- 在 404(未找到)上,它给了我一个
org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /test - 在 405 上(不允许的方法)它给了我一个
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported - 在 500(内部服务器错误)上它给了我一个
java.lang.ArithmeticException: / by zero
但是我现在如何才能找到正确的 http 状态代码?我可以在HttpServletRequest 或HttpServletResponse 中阅读它们吗?
因为当我可以从某个地方获得它们时,我可以将其设置为response.setStatus(...)。
但我在 stackoverflow 上发现的唯一内容是:
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
在我当前基于弹簧的解决方案中,这始终是null。 (在我的web.xml 解决方案中,可以通过这种方式读出状态码。但现在我的tomcat 不会抛出错误。现在spring 会在管道中更早地处理错误方式。)
那么我怎样才能在正确的情况下得到正确的http状态码呢?
感谢您的帮助:)
【问题讨论】:
-
你检查过@Autowired private ErrorAttributes errorAttributes;
标签: java spring spring-mvc error-handling