If at the request something went wrong, RestController throw out the RestController json :

 { "timestamp": 1510417124782, "status": 500, "error": "Internal Server Error", "exception": "com.netflix.hystrix.exception.HystrixRuntimeException", "message": "ApplicationRepository#save(Application) failed and no fallback available.", "path": "/application" } 

What class object was serialized for this? Can I somehow influence this object and enter the status and message of this object in runtime?

1 answer 1

I smoked tutorials and docks and this is what I understood:

The default is the json that we see is an object of the DefaultErrorAttributes class.

Setting your own rest handler is not so difficult. For this you need to know about the following things:

ResponseEntityExceptionHandler is the class that actually handles exception handling and decides what needs to be returned to the user. It has many methods with a name like handle + exception name.

ControllerAdvice is an annotation that gives "tips" to a group of controllers. In fact, it is a kind of hook for them. By default, annotation affects all controllers, but in its parameters there are options for specifying specific groups.

ExceptionHandler - annotation for catching certain errors.

Accordingly, in order to catch some exception, process it and give something to the user, you need to create a class with the annotation ControllerAdvice and inherit it from ResponseEntityExceptionHandler . Then override the desired exception.

Like this:

 @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) { return super.handleAsyncRequestTimeoutException(ex, headers, status, webRequest); } } 

In the event that we want to handle our own exception or some other specific exception not from the ResponseEntityExceptionHandler class, we can use the following construction:

 @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(HystrixRuntimeException.class) protected ResponseEntity<Object> handleHystrixRuntimeException(HystrixRuntimeException e) { HttpTypicalError error = getHttpTypicalError(e); return new ResponseEntity<>(new ErrorAnswer(error.getMessage()), HttpStatus.valueOf(error.getStatus())); } }