Java Spring ExceptionHandler Controller syntax and good practices - java

I would like to handle my exceptions correctly in Spring, so I have a question about exceptionHandler syntax : Is it ok to throw specific exceptions in the controller, if they are caught by the exception handler ?
More specifically :
Here is the Exception :
public class UnknownUserException extends Exception {
private static final long serialVersionUID = 1L;
public UnknownUserException(String message) {
super(message);
}
}
Here is the ExceptionHandler with the specific method for UnknownUserException :
#ControllerAdvice
#ResponseBody
public class ControllerExceptionHandler {
#ExceptionHandler(UnknownUserException.class)
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorMessage unknownUserExceptionMessage(UnknownUserException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage("The user doesn't exist: " +ex.getLocalizedMessage(), ex);
return message;
}
}
Here is one example of a mapping that may raise that exception :
#GetMapping({"/user/{id}"})
public ResponseEntity<UserProfileDto> getById(#PathVariable Long id) throws UnknownUserException {
UserProfileDto user = userService.findById(id);
return ResponseEntity.ok(user);
}
The userService.findById(id) may throw the UnknownUserException.
From what I understood, the controllerAdvice "overrides" the controller in case of that specific exception thrown by a service, but then, what should I do with my controller ? should I throw the exception again (like above) or catch the specific exception and return a ResponseEntity(HttpStatus.NOT_FOUND) ?

In an ideal scenario exception should be thrown immediately when it is known in your case as you mentioned service method will throw UnknownUserException that the right thing to do. Your Controller Advice should be able to handle that exception. ContollerAdvice will handle any matching exception that is thrown during execution of the request irrespective of the origin of exception.
Refer to this link for other options on handling exception

Related

How to add an Exception Handler for an exception type that could be custom or default

I have a use case where for certain exception's that are normally thrown by a web framework that I can override the value by using my own MyCustomException object.
#ExceptionHandler({SomeWebFrameworkException.class})
public ResponseEntity<Object> handleException(MyCustomException exception) { ... }
However, if I want an exception handler to be able to be able to accept my custom exception then, I would need to cover all cases of this web framework error being thrown. Is there a way to somehow make it accept MyCustomException as input otherwise just default to a normal Exception ? If I just use a simple Exception as the input then, it would end up getting treated as the SomeWebFrameworkException instead of my own.
#ExceptionHandler({SomeWebFrameworkException.class})
public ResponseEntity<Object> handleException(Exception exception1, MyCustomException exception2) { ... }
You can have multiple exception handling methods defined, similarly to catch-blocks
#ExceptionHandler(MyCustomException.class)
public ResponseEntity<Object> handleMyCustomException(MyCustomException exception) { ... }
#ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleGenericException(Exception exception) { ... }

Call global #ControllerAdvice method from controller #ExceptionHandler method

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;
}
}

Custom exception handler for status NotFound

I want to implement custom exception handler for status NotFoundException for Spring Boot:
#ExceptionHandler({ AccessDeniedException.class, NotFoundException.class })
public ResponseEntity<ErrorResponseDTO> accessDeniedExceptionHandler(final AccessDeniedException ex) {
......
}
I can't find what is the proper import for NotFoundException Do you know what exception what is the proper import for that case?
Either add an exception handler for a NoHandlerFoundException:
#ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<ErrorResponseDto> handle(NoHandlerFoundException e) {
// ...
}
Or have your controller advice extend ResponseEntityExceptionHandler and override the handleNoHandlerFoundException method.
By the way, your code snippet declares a handler for two different exceptions while the method parameter final AccessDeniedException ex explicitly expects an exception of type AccessDeniedException. I would suggest either declaring multiple handler methods or generalize the paramater to an Exception instead.
I agree with #Michiel on, method parameter(AccessDeniedException ex) should be parent class of below classes:
AccessDeniedException
NotFoundException
try this
#ExceptionHandler({ AccessDeniedException.class, NotFoundException.class })
public ResponseEntity<ErrorResponseDTO> accessDeniedExceptionHandler(final **Exception** ex) {
......
}
i have used #ControllerAdvice like
#ControllerAdvice
public class GlobalControllerExceptionHandler {
#ExceptionHandler({BadRequestException.class, IllegalArgumentException.class, MaxUploadSizeExceededException.class})
#ResponseBody
public ResponseEntity<ErrorResponse> handleBadRequestException(Exception exception, WebRequest request) {
String message = StringUtils.isEmpty(exception.getMessage()) ? properties.getGeneralMessages().get("fail") : exception.getMessage();
if (message.contains(";"))
message = message.substring(0, message.indexOf(";"));
return getResponseEntity(message, null);
}
}

How to get all exception handlers annotated by #ExceptionHanlder?

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...
}
}

Custom exception with spring not thrown

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 ???

Categories

Resources