Reputation: 2957
I want to prevent spring from sending complete stacktrace of Runtimexceptions to the front end. I did something like this:
@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;
}
}
My objective is to send just the error code and nothing else to the front end. The above method returns status 200 OK to front end. What should be returned instead of null ?
Upvotes: 2
Views: 2522
Reputation: 48837
With @ResponseStatus
, if providing only a value
, HttpServletResponse.setStatus(int)
is used:
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.
If providing a reason
as well, then HttpServletResponse.sendError(int, String)
is used instead.
@ControllerAdvice
public class RestErrorHandler {
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "INTERNAL_SERVER_ERROR")
@ExceptionHandler(Exception.class)
public void handleConflict(Exception e) {
// log me
}
}
Upvotes: 1