在阅读了一些关于为 Spring 制作自定义异常处理程序的博客文章后,我编写了以下类:
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseEntity<Object> exceptionHandler(Exception e) {
HashMap<String, Object> msg = new HashMap<>(2);
msg.put("error", HttpStatus.PRECONDITION_FAILED.value());
msg.put("message", "Something went wrong");
return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
}
}
目的是在 JSON 响应中发送 msg
,而不是放弃无论出于何种原因抛出的 Spring 异常。
但是,这个类不起作用。
当我点击服务器 API 的无效端点时,我会得到默认的响应负载:
{
"timestamp": 1449238700342,
"status": 405,
"error": "Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/bad_enpoint"
}
我错过了什么?
谢谢。
最佳答案
您的处理程序将不会被调用,因为您希望将 Exception
映射到您的自定义错误响应,但 Spring MVC 很可能已经为 Exception
类注册了一个异常处理程序。它还有一个可以处理 HttpRequestMethodNotSupportedException
的方法。
然而,覆盖整个 Spring MVC 异常处理/映射并不是一个好主意。您应该只关心特定的异常 - 您定义的异常。
请阅读this article更深入地了解 Spring MVC 异常处理。
关于java - @ExceptionHandler for type Exception not called for Spring exception in custom ResponseEntityExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40618372/