尽管有 @ResponseStatus 注释,ResponseEntityExceptionHandler 不会向客户端发送错误代码
ResponseEntityExceptionHandler does not send an error code to the client despite @ResponseStatus annotation
我想阻止 spring 将 Runtimexceptions 的完整堆栈跟踪发送到前端。我做了这样的事情:
@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception e, Object body,
HttpHeaders headers, HttpStatus status, WebRequest request) {
logger.error("Error happened while executing controller.", e);
return null;
}
}
我的objective是只向前端发送错误代码,不发送任何其他内容。以上方法returns status 200 OK 到前端。应该返回什么而不是 null ?
与@ResponseStatus
, if providing only a value
, HttpServletResponse.setStatus(int)
一起使用:
This method is used to set the return status code when there is no
error (for example, for the SC_OK or SC_MOVED_TEMPORARILY status
codes).
If this method is used to set an error code, then the container's
error page mechanism will not be triggered. If there is an error and
the caller wishes to invoke an error page defined in the web
application, then sendError(int, java.lang.String) must be used
instead.
如果提供 reason
as well, then HttpServletResponse.sendError(int, String)
则改为使用。
@ControllerAdvice
public class RestErrorHandler {
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "INTERNAL_SERVER_ERROR")
@ExceptionHandler(Exception.class)
public void handleConflict(Exception e) {
// log me
}
}
我想阻止 spring 将 Runtimexceptions 的完整堆栈跟踪发送到前端。我做了这样的事情:
@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception e, Object body,
HttpHeaders headers, HttpStatus status, WebRequest request) {
logger.error("Error happened while executing controller.", e);
return null;
}
}
我的objective是只向前端发送错误代码,不发送任何其他内容。以上方法returns status 200 OK 到前端。应该返回什么而不是 null ?
与@ResponseStatus
, if providing only a value
, HttpServletResponse.setStatus(int)
一起使用:
This method is used to set the return status code when there is no error (for example, for the SC_OK or SC_MOVED_TEMPORARILY status codes).
If this method is used to set an error code, then the container's error page mechanism will not be triggered. If there is an error and the caller wishes to invoke an error page defined in the web application, then sendError(int, java.lang.String) must be used instead.
如果提供 reason
as well, then HttpServletResponse.sendError(int, String)
则改为使用。
@ControllerAdvice
public class RestErrorHandler {
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "INTERNAL_SERVER_ERROR")
@ExceptionHandler(Exception.class)
public void handleConflict(Exception e) {
// log me
}
}