I'm trying to override the ResponseErrorHandler interface to be able to return the entire request (status code, body etc.) in case of any response other than 2xx.
I noticed that the Spring (RestTemplate) default returns an exception in case of a response other than 2xx. I do not want to return an exception, I just want to be able to return a:
new ResponseEntity(HttpStatus.STATUS_CODE)
Following some tutorials, I've found the following code:
#Component
public class LoginErrorHandler
implements ResponseErrorHandler {
#Override
public boolean hasError(ClientHttpResponse httpResponse)
throws IOException {
return (
httpResponse.getStatusCode().series() == CLIENT_ERROR
|| httpResponse.getStatusCode().series() == SERVER_ERROR);
}
#Override
public void handleError(ClientHttpResponse httpResponse)
throws IOException {
if (httpResponse.getStatusCode()
.series() == SERVER_ERROR) {
// handle SERVER_ERROR
} else if (httpResponse.getStatusCode()
.series() == CLIENT_ERROR) {
// handle CLIENT_ERROR
}
}
(Reference)
But I have not understood how I can return a ResponseEntity without changing the method return (which I can not by implementing the method).
Implementation:
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new LoginErrorHandler());
return restTemplate.postForEntity(url, request, String.class);
You can use Spring's ControllerAdvice and ExceptionHandler annotations to handle exceptions through your application. Below code returns 500 http status code if any exception encountered in your request. You can add other Exception classes or your own custom class to handle specific cases and return specific status codes to client.
Edit
Handling each code will not be a good idea. Rather you can wrap them in your custom exception and provide proper message to your client service. Still you can try something like below.
#Component
#ControllerAdvice
public class MyExceptionHandler {
#ExceptionHandler(HttpClientErrorException.BadRequest.class)
#ResponseStatus(code=HttpStatus.BAD_REQUEST, reason="Bad Request", value=HttpStatus.BAD_REQUEST)
public void handleBadRequest(HttpClientErrorException.BadRequest e) {
//handle bad request exception
}
#ExceptionHandler(HttpClientErrorException.NotFound.class)
#ResponseStatus(code=HttpStatus.NOT_FOUND, reason="Not Found", value=HttpStatus.NOT_FOUND)
public void handleNotFound(HttpClientErrorException.NotFound e) {
//handle Not Found
}
#ExceptionHandler(HttpServerErrorException.InternalServerError.class)
#ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error", value=HttpStatus.INTERNAL_SERVER_ERROR)
public void handleInternalServerError(HttpServerErrorException.InternalServerError e) {
//handle internal server error
}
//more methods for each code.
}
Then handle the codes from in your rest template as below. Here you won't be able to return body of the response to the client.
#Component
public class LoginErrorHandler
implements ResponseErrorHandler {
#Override
public boolean hasError(ClientHttpResponse httpResponse)
throws IOException {
return (httpResponse.getStatusCode() != HttpStatus.OK);
}
#Override
public void handleError(ClientHttpResponse httpResponse)
throws IOException {
if (httpResponse.getRawStatusCode() >=400 && httpResponse.getRawStatusCode()<500 ) {
throw HttpClientErrorException.create(httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), null, null);
}else if(httpResponse.getRawStatusCode() >=500){
throw HttpServerErrorException.create(httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), null, null);
}else {
//throw some other exceptions for other codes and catch them in controller advice.
}
}
}
You can do this:
#Component
#ControllerAdvice
public class LoginErrorHandler{
#ExceptionHandler(HttpClientErrorException.class)
#ResponseBody
public void handleError(HttpClientErrorException e, HttpServletResponse response) throws IOException {
response.sendError(e.getRawStatusCode(), e.getStatusText());
}
}
This you generify all status code that should drop an exception, and it will return in the body.
There are two extensively used and very convenient exception handlers which are provided by Spring framework for centralized exception management in Spring Boot applications.
ResponseEntityExceptionHandler : exception thrown by our endpoint methods(methods annotated with #RequestMapping)
A convenient base class for #ControllerAdvice classes that wish to provide centralized exception handling across all #RequestMapping methods through #ExceptionHandler methods.
ResponseErrorHandler : Spring provides a hook ResponseErrorHandler which can be implemented to handle the exception thrown by external services. To call any external service most likely you will be using a RestTemplate. A RestTemplate can throw three types of exception as listed below :
HttpClientErrorException : For 4xx series status codes or Client errors.
HttpServerErrorException : For 5xx series status codes or server errors
RestClientException : Any other status codes like 3xx series
To simplify things we can handle these exceptions as a catch block separately but it lead to lot of boilerplate code scattered across our service. Strategy interface used by the RestTemplate to determine whether a particular response has an error or not.
There are two steps to using ResponseErrorHandler :
Step 1: Create a custom error handler class by implementing ResponseErrorHandler and implements its methods hasError and handleError
Step 2: We need to inject the ResponseErrorHandler implementation into the RestTemplate instance as follows :
By default in RestTemplate the errorHandler points to DefaultResponseErrorHandler.
Source
Related
Is it possible to handle exceptions in a controller using #ExceptionHandler and then rethrow that exception so a #ControllerAdvice can handle it?
I am trying to do it but when I rethrow the exception it doesn't reach the ControllerAdvice.
#RestController
public class MyController {
#GetMapping
public Something getSomething() {
...
}
#ExceptionHandler(Exception.class)
public void handleException(Exception e) throws Exception {
System.out.println("Log!");
throw e;
}
#RestControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(Exception.class)
public ResponseEntity<...> handleException(Exception exception) {
// Not working
...
}
Some more context (hopefully you can give me some different ideas on implementing this):
Today our application has a GlobalExceptionHandler (annotated with RestControllerAdvice) that handles exceptions.
Now, we have a new business demand that 2 particular endpoints we have must now log some additional info like "endpoint GET /something got this error".
Any kind of exception must be logged, I need to log which particular endpoint it happened and I need to keep the global handler in place as it is responsible for creating the error responses.
One way to solve this would be to change each method on the global handler to inject the current request, retrieve the url from it, check a particular configuration if I need to log for that endpoint and log it, but it feels wrong adding this behaviour to all handler methods.
Can you use the aspect of AOP and wrap your request with catch an any exceptions?
#Aspect
#Component
public class RequestWrapperAspect {
#Around("(#annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
"#annotation(org.springframework.web.bind.annotation.PostMapping) || " +
"#annotation(org.springframework.web.bind.annotation.PutMapping) || " +
"#annotation(org.springframework.web.bind.annotation.DeleteMapping) || " +
"#annotation(org.springframework.web.bind.annotation.GetMapping) || " +
"#annotation(org.springframework.web.bind.annotation.PatchMapping)) && execution(public * *(..))")
public Object wrapRequest(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
try {
return proceedingJoinPoint.proceed();
} catch (Exception e) {
//whatever you need to do
throw e;
}
}
I have a MVC controller having at least 50 functions in there and my call to the services are not wrapped around try catch and some of the exceptions are getting eaten. I am trying to find the best way to handle this.
Shall I wrap the calls around try catch in individual function or is there any function I can use that can log the exception. I dont want to send alternate view or something just simply want to record in the logs.
You should probably look at #ExceptionHandler (controller-based exception Handling) or #ControllerAdvice (global exception handling). This article explains both in detail.
The other possible solution is AOP.
You could extend SimpleMappingExceptionResolver and override logException() like this:
public class CustomExceptionResolver extends SimpleMappingExceptionResolver {
#Override
protected void logException(Exception ex, HttpServletRequest request) {
if (ex != null) {
logger.error(ex);
}
}
}
However, if the exception occurs in the view, the above will not log it. For this, you can extend HandlerInterceptorAdapter:
public class ViewExceptionLoggerInterceptor extends HandlerInterceptorAdapter {
protected final Log logger = LogFactory.getLog(getClass());
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (ex != null) {
logger.error(ex);
}
}
}
To centralize exception handling, use the follow:
#ControllerAdvice
public class MyExceptionHandler{
#ExceptionHandler(SomeException.class)
public final ResponseEntity<ReturnValue> handleSomeException(SomeException ex) {
// exception handling
}
}
If you need ModelAndView as a return value, just change the return type to it, and build the proper object in the body.
How to get all exception handlers annotated by #ExceptionHanlder and I can call them manually?
Background
I need to handle some exceptions by my own exception handlers but in some situation my handled exceptions are not thrown directly by spring, and they are wrapped in the cause by. So I need to handle these caused by exceptions in one place using my own exception handling strategy in the existing #ExceptionHandlers. How can I do that?
Try to use Java Reflection Api to find classes annotated with "ExceptionHanlder". And invoke any method or whatever you want.
You can extend ResponseEntityExceptionHandler and make it a #ControllerAdvise like below.
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler({YourException.class})
public ResponseEntity<Object> handleMyException(Exception ex, WebRequest request) {
... handle the way you like it
return new ResponseEntity<Object>(YourErrorObject, new HttpHeaders(), HttpStatus);
}
}
Spring provides #ControllerAdvice annotation that we can use with any class to define our global exception handler. The handler methods in Global Controller Advice is same as Controller based exception handler methods and used when controller class is not able to handle the exception.
You want to use exception handling strategy in your one place. that you can define multiple exception or make message using exception in exception controller.
like this :
#ExceptionHandler(value = { HttpClientErrorException.class, HTTPException.class, HttpMediaTypeException.class,
HttpMediaTypeNotSupportedException.class, HttpMessageNotReadableException.class })
or
#ExceptionHandler
#ResponseBody
ExceptionRepresentation handle(Exception exception) {
ExceptionRepresentation body = new ExceptionRepresentation(exception.getLocalizedMessage());
HttpStatus responseStatus = resolveAnnotatedResponseStatus(exception);
return new ResponseEntity<ExceptionRepresentation>(body, responseStatus);
}
HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
if (annotation != null) {
return annotation.value();
}
return HttpStatus.INTERNAL_SERVER_ERROR;
}
Here is a work around. You can catch the the wrapping exception and then check the root cause of the exception. Here is an example of MySQLIntegrityConstraintViolationException which is wrapped by DataIntegrityViolationException in spring:
#ExceptionHandler(DataIntegrityViolationException.class)
#ResponseBody
public ResponseEntity<Object> proccessMySQLIntegrityConstraint(DataIntegrityViolationException exception) {
if (exception.getRootCause() instanceof MySQLIntegrityConstraintViolationException) {
doSomething....
} else {
doSomethingElse...
}
}
I want to let HandlerExceptionResolver resolve any Exceptions that I don't explicit catch via #ExceptionHandler annotation.
Anyways, I want to apply specific logic on those exceptions. Eg send a mail notification or log additionally. I can achieve this by adding a #ExceptionHandler(Exception.class) catch as follows:
#RestControllerAdvice
public MyExceptionHandler {
#ExceptionHandler(IOException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
public Object io(HttpServletRequest req, Exception e) {
return ...
}
#ExceptionHandler(Exception.class)
public Object exception(HttpServletRequest req, Exception e) {
MailService.send();
Logger.logInSpecificWay();
//TODO how to continue in the "normal" spring way with HandlerExceptionResolver?
}
}
Problem: if I add #ExceptionHandler(Exception.class) like that, I can catch those unhandled exceptions.
BUT I cannot let spring continue the normal workflow with HandlerExceptionResolver to create the response ModelAndView and set a HTTP STATUS code automatically.
Eg if someone tries a POST on a GET method, spring by default would return a 405 Method not allowed. But with an #ExceptionHandler(Exception.class) I would swallow this standard handling of spring...
So how can I keep the default HandlerExceptionResolver, but still apply my custom logic?
To provide a complete solution: it works just by extending ResponseEntityExceptionHandler, as that handles all the spring-mvc errors.
And the ones not handled can then be caught using #ExceptionHandler(Exception.class).
#RestControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(Exception.class)
public ResponseEntity<Object> exception(Exception ex) {
MailService.send();
Logger.logInSpecificWay();
return ... custom exception
}
}
Well, I was facing the same problem some time back and have tried several ways like extending ResponseEntityExceptionHandler but all them were solving some problems but creating other ones.
Then I have decided to go with a custom solution which was also allowing me to send additional information and I have written below code
#RestControllerAdvice
public class MyExceptionHandler {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#ExceptionHandler(NumberFormatException.class)
public ResponseEntity<Object> handleNumberFormatException(NumberFormatException ex) {
return new ResponseEntity<>(getBody(BAD_REQUEST, ex, "Please enter a valid value"), new HttpHeaders(), BAD_REQUEST);
}
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException ex) {
return new ResponseEntity<>(getBody(BAD_REQUEST, ex, ex.getMessage()), new HttpHeaders(), BAD_REQUEST);
}
#ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<Object> handleAccessDeniedException(AccessDeniedException ex) {
return new ResponseEntity<>(getBody(FORBIDDEN, ex, ex.getMessage()), new HttpHeaders(), FORBIDDEN);
}
#ExceptionHandler(Exception.class)
public ResponseEntity<Object> exception(Exception ex) {
return new ResponseEntity<>(getBody(INTERNAL_SERVER_ERROR, ex, "Something Went Wrong"), new HttpHeaders(), INTERNAL_SERVER_ERROR);
}
public Map<String, Object> getBody(HttpStatus status, Exception ex, String message) {
log.error(message, ex);
Map<String, Object> body = new LinkedHashMap<>();
body.put("message", message);
body.put("timestamp", new Date());
body.put("status", status.value());
body.put("error", status.getReasonPhrase());
body.put("exception", ex.toString());
Throwable cause = ex.getCause();
if (cause != null) {
body.put("exceptionCause", ex.getCause().toString());
}
return body;
}
}
Create classes for exception handling in this way
#RestControllerAdvice
public class MyExceptionHandler extends BaseExceptionHandler {
}
public class BaseExceptionHandler extends ResponseEntityExceptionHandler {
}
Here ResponseEntityExceptionHandler is provided by spring and override the several exception handler methods provided by it related to the requestMethodNotSupported,missingPathVariable,noHandlerFound,typeMismatch,asyncRequestTimeouts ....... with your own exception messages or error response objects and status codes
and have a method with #ExceptionHandler(Exception.class) in MyExceptionHandler where the thrown exception comes finally if it doesn't have a matching handler.
I had the same issue and solved it creating a implementation of the interface HandlerExceptionResolver and removing the generic #ExceptionHandler(Exception.class) from the generic handler method.
.
It works this way:
Spring will try to handle the exception calling MyExceptionHandler first, but it will fail to find a handler because the annotation was removed from the generic handler. Next it will try other implementations of the interface HandlerExceptionResolver. It will enter this generic implementation that just delegates to the original generic error handler.
After that, I need to convert the ResponseEntity response to ModelAndView using MappingJackson2JsonView because this interface expects a ModelAndView as return type.
#Component
class GenericErrorHandler(
private val errorHandler: MyExceptionHandler,
private val objectMapper: ObjectMapper
) : HandlerExceptionResolver {
override fun resolveException(request: HttpServletRequest, response: HttpServletResponse, handler: Any, ex: Exception): ModelAndView? {
// handle exception
val responseEntity = errorHandler.handleUnexpectedException(ex)
// prepare JSON view
val jsonView = MappingJackson2JsonView(objectMapper)
jsonView.setExtractValueFromSingleKeyModel(true) // prevents creating the body key in the response json
// prepare ModelAndView
val mv = ModelAndView(jsonView, mapOf("body" to responseEntity.body))
mv.status = responseEntity.statusCode
mv.view = jsonView
return mv
}
}
I wrote a custom exception with Spring 5 reactive
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class AddressNotFoundException extends RuntimeException{
public AddressNotFoundException(String message) {
super(message);
}
and I call this one in a service:
#Override
public Mono<Address> getById(String id) {
Address addressFound=repository.findById(id).block();
if(Objects.equals(addressFound, null))
throw new AddressNotFoundException("Address #"+id+" not found");
return Mono.just
(addressFound);
}
but when I reach this page an exception is thrown but it's not a 404 but a null pointer exception and a error 500 page but with the correct message ?
The AddressNotFound is never thrown, only the Nullpointer exception but with my custom message ???
Can you help me please ?
Here is my controller :
#GetMapping("/address/{id}")
public Mono<Address> byId(#PathVariable String id) {
return addressService.getById(id);
}
Thanks
if your address is null,
repository.findById(id).block();
Should be throwing the NullPointerException I suppose. In that way it could never reach the code line to throw the custom exception.
Instead of extending RuntimeException try extending just generic Exception.
Spring offers a ControllerAdvice annotation to intercept exceptions that are thrown
#ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {
#ExceptionHandler(value = { AddressNotFoundException.class })
protected ResponseEntity<Object> handleAddressNotFoundException(Exception ex, WebRequest request) {
AddressNotFoundException notFound = (AddressNotFoundException)ex;
return handleExceptionInternal(ex, String.valueOf(notFound), new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
This will send the error back to the client as a 404 in which you can digest on the client side to display to the user typically in the form of a json string. Can either override the exceptions toString method to return it as a json or write a helper method that would do that.
You probably have a HandlerExceptionResolver bean which is causing 500 for some reason. Please try taking that off for a while.
I've tried with spring boot 1.5 it works with Spring Boot 2 without webflux it works, so it seems that Webflux can't handle custom exception ???