spring引导覆盖默认的REST异常处理程序 [英] spring boot override default REST exception handler
问题描述
我无法覆盖REST API中的默认弹簧启动错误响应。我有以下代码:
@ControllerAdvice
@Controller
class ExceptionHandlerCtrl {
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY,reason =无效数据)
@ExceptionHandler(BusinessValidationException.class)
@ResponseBody $ b $ public ResponseEntity< BusinessValidationErrorVO> handleBusinessValidationException(BusinessValidationException异常){
BusinessValidationErrorVO vo = new BusinessValidationErrorVO()
vo.errors = exception.validationException
vo.msg = exception.message
def result = new ResponseEntity<> ;(vo,HttpStatus.UNPROCESSABLE_ENTITY);
结果
}
然后在我的REST API中,我抛出这个BusinessValidationException。这个处理程序被调用(我可以在调试器中看到它),但是我仍然得到了默认的spring引导REST错误消息。有没有办法重写和使用默认只作为后备? Spring Boot版本1.3.2与Groovy。最好的问候
从您的方法中删除 @ResponseStatus
由于您在 ResponseEntity
中设置 HttpStatus.UNPROCESSABLE_ENTITY
,所以会产生不良副作用, 。
警告:在异常类上使用此批注或设置此批注的reason属性时,将使用
HttpServletResponse.sendError
方法。 / p>
使用
HttpServletResponse.sendError
,响应被认为是完整的,不应再写入。此外, Servlet容器通常会编写一个HTML错误页面,因此使用了一个不适合REST API的原因。对于这种情况,最好使用ResponseEntity
作为返回类型,并避免使用@ResponseStatus
。 / strong>
I am not able to override default spring boot error response in REST api. I have following code
@ControllerAdvice
@Controller
class ExceptionHandlerCtrl {
@ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Invalid data")
@ExceptionHandler(BusinessValidationException.class)
@ResponseBody
public ResponseEntity<BusinessValidationErrorVO> handleBusinessValidationException(BusinessValidationException exception){
BusinessValidationErrorVO vo = new BusinessValidationErrorVO()
vo.errors = exception.validationException
vo.msg = exception.message
def result = new ResponseEntity<>(vo, HttpStatus.UNPROCESSABLE_ENTITY);
result
}
Then in my REST api I am throwing this BusinessValidationException. This handler is called (I can see it in debugger) however I still got default spring boot REST error message. Is there a way to override and use default only as fallback? Spring Boot version 1.3.2 with groovy. Best Regards
Remove @ResponseStatus
from your method. It creates an undesirable side effect and you don't need it, since you are setting HttpStatus.UNPROCESSABLE_ENTITY
in your ResponseEntity
.
From the JavaDoc on ResponseStatus
:
Warning: when using this annotation on an exception class, or when setting the reason attribute of this annotation, the
HttpServletResponse.sendError
method will be used.With
HttpServletResponse.sendError
, the response is considered complete and should not be written to any further. Furthermore, the Servlet container will typically write an HTML error page therefore making the use of a reason unsuitable for REST APIs. For such cases it is preferable to use aResponseEntity
as a return type and avoid the use of@ResponseStatus
altogether.
这篇关于spring引导覆盖默认的REST异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!