Order of #ExceptionHandler - java

I use #ControllerAdvice to handle all my app exceptions :
#ControllerAdvice
public class ExceptionHandlingController {
#ExceptionHandler({UnauthorizedException.class})
public String unauthorizedException() {
.........
}
#ExceptionHandler({UnauthorizedAjaxException.class})
#ResponseBody
public void unauthorizedAjaxException() {
.........
}
#ExceptionHandler({Exception.class})
public String globalException(){
.........
}
}
And somewhere in my code i do throw new UnauthorizedException();
#Around("#annotation(Authenticated)")
public Object profilingAuthentication(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
if( request.getSession().getAttribute("idContact") == null ) {
if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) )
throw new UnauthorizedAjaxException();
throw new UnauthorizedException();
}
return pjp.proceed();
}
But sadly Spring MVC appears to be acting random by using the most generic case (Exception) rather than more specific ones (UnauthorizedException for example). And sometimes he choose the correct one !
How the order works works ? and is there any way to specify the order ?
UnauthorizedException is a custom exception
public class UnauthorizedException extends Exception {
public UnauthorizedException(){
super();
}
public UnauthorizedException(String message){
super(message);
}
}
UPDATE
i found out that the order it's not rondom actually the methods who throw UnauthorizedException works normally but the others not !
#Authenticated
#RequestMapping(value="/favoris")
public String favoris(ModelMap model, HttpServletRequest request)
throws UnauthorizedException {
....
}
#Authenticated
#RequestMapping(value="/follow")
public String follow(ModelMap model, HttpServletRequest request) {
.....
}
So i have to add throws UnauthorizedException manually or there is some other solution ?

we are using exception handler in following way and never order get mixed and it work as expected.
So it could be possible if you will use it as following example then it will solve your problems
**********handler class******************
#ControllerAdvice
public class GlobalExceptionHandler {
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
#ExceptionHandler(value = Exception.class)
public boolean handle1(Exception exc) {
System.out.println("#####Global Exception###" + exc);
exc.printStackTrace(System.out);
return true;
}
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
#ExceptionHandler(value = CustomException.class)
public boolean handle2(CustomException exc) {
System.out.println("###custom exception######" + exc);
exc.printStackTrace(System.out);
return true;
}
}
***************Controller class************
#RestController("test")
#RequestMapping("/test1")
public class TestController {
#RequestMapping("/t1")
public boolean test() {
if (true) {
throw new CustomException();
}
return true;
}
}
In above example exception habdler is handle2 because 1st of all it will search for matching exception if not found then go for parrent handler
If we throw new NullPointerException() then it will search for matching handler but not found in this case then go for parrent that is handle1
for more you can refer here
I hope it will help you. Thanks

Use an annotation #Order or implement an interface Ordered for #ControllerAdvice.
See implementations of:
ExceptionHandlerMethodResolver class
ExceptionHandlerExceptionResolver class (method initExceptionHandlerAdviceCache)
AnnotationAwareOrderComparator class

There is no order/priority as long as you have a single controlleradvice class in your project. But if you have multiple controlleradvice classes, you can set the Order. But here, in your case, the order is not applicable as the two exceptions are handled differently (i.e., UnauthorizedException and Exception).
The good thing is, Spring will automatically find the respective custom Exception class (if any,
otherwise generic Exception) and invoke the corresponding method.
Please refer for more information on Spring Controller Advice and Exception handling:
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Related

How to handle Exception in controller for Spring Boot REST API?

I am confused of how I should handler the exception of the controller in a Spring Boot Rest API. Right now I throw some exception in my service classes like this:
public Optional<Item> getSpecificItem(Long itemId) throws Exception {
return Optional.ofNullable(itemRepository.findById(itemId).
orElseThrow(() -> new Exception("Item with that id doesn't exist")));
}
I don't know if this is the correct way to do it but it kind of works, I am open to criticism. For the controller classes I don't know how it should look, I saw some example with #ControllerAdvice and exception for each controller and that looked kind of bad to me. Can I have a global exception class for all controllers? Is it good practice ?
Saw some examples and I don't know if they were the correct way to do it.
#ControllerAdvice is good if you not use for general Exception. Example, if you define spec exception such as SkyIsRedException. So, it will be throw anywhere it will catch.
#ControllerAdvice
public class ExampleAdvice {
#ExceptionHandler(SkyIsRedException.class)
#ResponseCode(HttpStatus.NOT_FOUND) // <- not required
public void methodName1() { ... }
#ExceptionHandler(SkyIsGreenException.class)
public void methodName2() { ... }
}
And you can this #ExceptionHandler in controller too, so it will activate if any methods of controller will throw this SkyIsRedException.
I not recommend use Exception for everything. You are only harming yourself.
UPDATE:
// annotations
public class Controller {
// annotations
public Optional<Item> getSpecificItem(Long itemId) throws ItemNotExistException {
return Optional.ofNullable(itemRepository.findById(itemId).
orElseThrow(() -> new ItemNotExistException("Item with that id doesn't exist")));
}
// Controller specific exception handler, not central like #ControllerAdvice
#ExceptionHandler(ItemNotExistException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public String itemNotExistExceptionHandler(ItemNotExistException ex) {
return ex.getMessage(); // example
{
}

Rejecting GET requests with additional query params

I have an HTTP GET endpoint that accepts some query parameters:
#GetMapping("/cat")
public ResponseEntity<Cat> getCat(#RequestParam("catName") String catName){ ...
If the clients will send additional query parameters, the endpoint will ignore them.
GET .../cat?catName=Oscar Getting Oscar
GET .../cat?catName=Oscar&gender=male Getting Oscar
GET .../cat?catName=Oscar&x=y Getting Oscar
I want to reject HTTP requests that will send additional query parameters:
GET .../cat?catName=Oscar OK
GET .../cat?catName=Oscar&gender=male Reject (HTTP error code XYZ)
GET .../cat?catName=Oscar&x=y Reject (HTTP error code XYZ)
I can change the signature of the method to accept a map and validate the values in the map as suggested here.
Is there a way to do with while keeping the cleaner and self explained method signature?
You can try to implement a HandlerInterceptor and validate such rule in preHandle(). If the request contains the query parameters that does not defined in the controller method , you just throw a specific type of Exception and configure a #ControllerAdvice to handle this exception. Something like :
public class FooHandlerInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
Set<String> allowQueryParams = Stream.of(hm.getMethodParameters())
.map(p -> p.getParameterAnnotation(RequestParam.class))
.map(req -> req.value())
.collect(toSet());
for (String currentRequestParamName : request.getParameterMap().keySet()) {
if (!allowQueryParams.contains(currentRequestParamName)) {
throw new FooRestException();
}
}
}
return true;
}
}
And the #ControllerAdvice to handle the Exception :
#ControllerAdvice
public class FooExceptionHandler {
#ExceptionHandler(FooRestException.class)
public ResponseEntity<Object> handle(FooRestException ex) {
return new ResponseEntity<>("Some query parameter are not defined", HttpStatus.BAD_REQUEST);
}
}
Finally register FooHandlerInterceptor to use it :
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooHandlerInterceptor());
}
}
I just show you the idea. You can further tweak the codes in HandlerInterceptor if you want such checking is only applied to a particular controller method.

Is there a good example of zalando-problem implementation in spring boot?

We are using zalando-problem for exception handling in our spring-boot application. but looks like our problem handlers are never called. Instead spring boot returns 500 Internal server error for all the exceptions. If you can provide some examples it will be helpful. I couldn't find a good example of zalando-problem implementation in spring boot
If the user is not logged in, the code is throwing SSOAuthenticationException exception.
#Immutable
public class SSOAuthenticationException extends AbstractThrowableProblem {
private final String errorMessage;
public SSOAuthenticationException( final String errorMessage ) {
super( ErrorConstants.SSO_CACHE_AUTHENTICATION_FAILED, errorMessage, Status.UNAUTHORIZED );
this.errorMessage = errorMessage;
}
public String getErrorMessage(){
return errorMessage;
}
#Override
public String toString() {
return "SSOAuthenticationException{}";
}
}
And the Exception handling code:
#ControllerAdvice
public class ExceptionTranslator implements ProblemHandling {
#Override
public ResponseEntity<Problem> process(#Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
if (entity == null) {
return entity;
}
Problem problem = entity.getBody();
if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
return entity;
}
ProblemBuilder builder = Problem.builder()
.withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
.withStatus(problem.getStatus())
.withTitle(problem.getTitle())
.with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());
if (problem instanceof ConstraintViolationProblem) {
builder
.with("violations", ((ConstraintViolationProblem) problem).getViolations())
.with("message", ErrorConstants.ERR_VALIDATION);
} else {
builder
.withCause(((DefaultProblem) problem).getCause())
.withDetail(problem.getDetail())
.withInstance(problem.getInstance());
problem.getParameters().forEach(builder::with);
if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
builder.with("message", "error.http." + problem.getStatus().getStatusCode());
}
}
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
}
#ExceptionHandler(SSOAuthenticationException.class)
#ResponseBody
public ResponseEntity<Problem> handleUnAuthenticatedUser(SSOAuthenticationException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.UNAUTHORIZED)
.with("message", ErrorConstants.SSO_CACHE_AUTHENTICATION_FAILED)
.build();
return create(ex, problem, request);
}
}
When I run in debugger, I notice that the exception handler is never called. instead the code thinks there is no handler registered (In ServletInitialHandler.java, it goes to the else section which is for exception not handled) and changes the status code to INTERNAL_SERVER_ERROR. So for all the exceptions, the application throws error 500. What is wrong in the exception handling code? Do we have to include a AdviceTrait? I tried that as well. but looks like that is also not working. If you could explain the right way of handling this exception and an example, it helps. Thanks
Using Problem Spring Web 0.25.2, I first created a new AdviceTrait similar to the existing ones:
public interface CustomAdviceTrait extends AdviceTrait {
#ExceptionHandler
default ResponseEntity<Problem> handleCustomException(final CustomException exception, final NativeWebRequest request) {
return create(Status.INTERNAL_SERVER_ERROR, exception, request);
}
}
This is also where a conversion into a Problem could take place, if needed.
Then, likewise to enabling dedicated built-in advice traits I enable them by implementing the respective interface on my ExceptionHandler:
#ControllerAdvice
public class FootlooseServiceExceptionHandler implements ProblemHandling, CustomAdviceTrait { }

Java Jersey PathParams Checking and NotFoundException custom message

I am using Jersey for rest API, JerseyTests to unit test.
I have been following what seems to be conventional practice over the internet for PathParams checking and Exception Handling, but I don't quite understand what I am doing wrong here:
RoomApplicationResource.java
#Path("demandes")
public class RoomApplicationResource {
#GET
#Path("/{email}/{requestNumber}")
public Response getRoomApplication(
#PathParam("email") String email,
#PathParam("requestNumber") String requestNumber) throws NoRoomApplicationFoundException {
if (email == "wrong#email.com" || requestNumber == "wrong") {
throw new NoRoomApplicationFoundException("bad request");
}
String response =requestNumber+" is valid for "+email;
return Response.ok(response).build();
}
}
I handle Exceptions like this:
NotFoundMapper.java
#Provider
public class NotFoundMapper implements ExceptionMapper<NoRoomApplicationFoundException>{
#Override
public Response toResponse(NoRoomApplicationFoundException e) {
return Response.status(Response.Status.NOT_FOUND)
.entity(e.getMessage()).build();
}
}
NoRoomApplicationFoundException.java
public class NoRoomApplicationFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NoRoomApplicationFoundException() {
super();
}
public NoRoomApplicationFoundException(String msg) {
super(msg);
}
public NoRoomApplicationFoundException(String msg, Exception e) {
super(msg, e);
}
}
And I test like this:
RoomApplicationResourceTest.java
public class RoomApplicationResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(RoomApplicationResource.class, NotFoundMapper.class);
}
// This test works fine as expected
#Test
public void whenParametersAreExistantReturnTheOkResponse() {
final Response res = target("demandes").path("valid#email.com").path("12345").request().get();
assertEquals(200, res.getStatus());
assertEquals("12345 is valid for valid#email.com", res.readEntity(String.class));
}
// This does not work as expected
#Test
public void whenEmailParameterDoNotMatchToAnyRoomApplicationThenReturns404() {
final Response res = target("demandes").path("wrong#email.com").path("12345").request().get();
assertEquals(404, res.getStatus());
assertEquals("bad request", res.readEntity(String.class));
}
}
Question 1: Is this way of doing conditional checking on params wrong? The result of the second test where the email is invalid should throw my custom exception and return a 404, but instead returns a 200 and the valid message.
Question 2: How should I handle missing parameters in this case? It seems Jersey throws a NotFoundException by default. Is there a simple way to customize the message of that error or perhaps use my custom exception as the throws NoRoomApplicationFoundException at the end of my resource method does not seem to be doing anything?
Thanks in Advance. Alex
Question 1
Yes. The problem is your use of == to compare Strings. You should instead be using String.equals(). See How do I compare Strings in Java?
if ("wrong#email.com".equals(email) || "wrong".equals(requestNumber)) {
throw new NoRoomApplicationFoundException("bad request");
}
Question 2:
This question seems to be related to your first question. But for me, as a general rule (this is just me), if I am authoring the exception class and the exception is specific to my JAX-RS application (meaning I will have no use for it outside the JAX-RS application), I will just make the exception extend WebApplicationException. This exception will be handled by default, and you can create the Response in that class. No need for any ExceptionMapper. For example
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class NoRoomApplicationFoundException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public NoRoomApplicationFoundException() {
this("Room not found", 400);
}
public NoRoomApplicationFoundException(String msg, int status) {
this(Response.status(status).entity(msg).build());
}
public NoRoomApplicationFoundException(Response response) {
super(response);
}
}
You could completely get rid of the NotFoundMapper and this would work just fine.
if ("wrong#email.com".equals(email) || "wrong".equals(requestNumber)) {
throw new NoRoomApplicationFoundException();
}
Some Resources:
Jersey Documentation for Exception Handling
WebApplicationException Javadoc to see different constructors. There are alot more ways you can construct your exception and chain up to the super class
What should I return if my object is null?. In general, if a resource can't be found, the general rule of thumb is to return a 404 Not Found. Not sure it applies to this specific case though.

Spring MVC: bind an exception handler to particular method

Good day!
I have a #Controller. Some of its methods throw the same exception, but I want to handle this exceptions in different way.
Is there a way how to bind an #ExceptionHandler to a particular method?
You need to use AOP tools like CDI Interceptor or AspectJ to achieve this cross-cutting concerns. A Concern is a term that refers to a part of the system divided on the basis of the functionality.
Basically this type of feature is used to handle logging, security and also handling the errors... which are not part of your business logic...
Like if you want to change the logger for application from log4j to sl4j then you need to go through each and every classes where you have used log4j and change it. But if you have used AOP tools then you only need to go the interceptor class and change the implementation. Something like plug and play and very powerful tool.
Here is a code snippet using JavaEE CDI Interceptor
/*
Creating the interceptor binding
*/
#InterceptorBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface BindException {
}
After we have define interceptor binding we need to define interceptor binding implementation
/*
Creating the interceptor implementation
*/
#Interceptor
#BindException
public class ExceptionCDIInterceptor {
#AroundInvoke
public Object methodInterceptor(InvocationContext ctx) throws Exception {
System.out.println("Invoked method " + ctx.getMethod().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// code for Exception handler
}
}
}
Now we only need to apply interceptor to our method
/*
Some Service class where you want to implement the interceptor
*/
#ApplicationScoped
public class Service {
// adding annotation to thisMethodIsBound method to intercept
#BindException
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionCDIInterceptor
}
}
You can achieve same feature using AspectJ also.
/*
Creating the Aspect implementation
*/
#Aspect
public class ExceptionAspectInterceptor {
#Around("execution(* com.package.name.SomeService.thisMethodIsBound.*(..))")
public Object methodInterceptor(ProceedingJoinPoint ctx) throws Throwable {
System.out.println("Invoked method " + ctx.getSignature().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// codes for Exception handler
}
}
}
Now we only need to enable the AspectJ to our application config
/*
Enable the AspectJ in your application
*/
#Configuration
#EnableAspectJAutoProxy
public class AppConfig {
#Bean
public SomeService SomeService() {
return new SomeService();
}
}
/*
Some Service class where you want to implement the Aspect
*/
package com.package.name;
public class SomeService {
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionAspectInterceptor
}
}
I have code example in my git repo https://github.com/prameshbhattarai/javaee-exceptionBinding by using CDI interceptor.
Just as an option (obviously, it's not ideal): you can wrap the exception into a custom exception in one of your methods and then catch it in an #ExceptionHandler
void boo() throws WrappingException {
try {
} catch (TargetException e) {
throw new WrappingException(e);
}
}
then
#ExceptionHandler(WrappingException.class)
public void handleWrappingException() {
// handle
}
#ExceptionHandler(TargetException.class)
public void handleTargetException() {
// handle
}
Could you please explain why do you need this? I'm asking out of curiosity, because I've never felt like this is required and here is why:
Exception usually represents a very specific "mistake" - something that went wrong in a very specific way.
Basically, exception represents a mistake, not a flow...
There are two "degrees of freedom" that spring can support out of the box:
Exception parameters. Maybe stuff like error code, which can be declared as a data field of exception itself.
Exception inheritance. Example:
If you have in your system a UserDoesNotExistException and you want to be more specific in a case of say, the system that manages the users that are retired in some flows, you can always create a more specific exception:
class UserRetiredException extends UserDoesNotExistException {...}
Obviously, spring can support both the cases: In ExceptionMapper you have the access to the exception anyway so you can do something like:
handleException(SomeExceptionWithErrorCode ex) {
if(ex.getErrorCode() == "A") {
// do this
}
else if(ex.getErrroCode() == "B") {
// do that
}
}
In the second case you just have different exception mappers for the different types of exceptions.
You can also consider #ControllerAdvice annotation to reuse code or something.
I don't think you can specify a specific #ExceptionHandler for a method, but you can bind an #ExceptionHandler method to a specific Exception.
So if you want to handle all DataIntegrityViolationException one way and all other Exceptions in another you should be able to achieve that with something like this:
#ExceptionHandler(DataIntegrityViolationException.class)
public void handleIntegrityViolation() {
// do stuff for integrity violation here
}
#ExceptionHandler(Exception.class)
public void handleEverythingElse() {
// do stuff for everything else here
}
You can derive sub-exceptions from the common exception thrown by other methods according to how you want to handle them.
Say you have declared the parent exception as ParentException. Derive sub classes like ChildAException extends ParentException, ChildBException extends ParentException etc.
Define a #ControllerAdvice class that catches the ParentException and define the specific behaviors in delegate methods.
#ControllerAdvice
public class ParentExceptionHandler {
#ExceptionHandler(ParentException.class)
public ResponseEntity<Object> handleParentException(ParentException pe) {
if (pe instanceof ChildAException) {
return handleChildAException((ChildAException) pe);
} else if (...) {
...
} else {
// handle parent exception
}
}
private ResponseEntity<Object> handleChildAException(ChildAException cae) {
// handle child A exception
}
}
I just got the same issue like you. So I checked the spring source code for this situation. It seems that spring will search in the #Controller class for any method that is annotated with #ExceptionHandler first, if nothing matched then it will continue to search for all class that is annotated with #ControllerAdvice. So you can just use the strategy below:
MyController with a #ExceptionHandler method:
#RestController
public class MyController {
#RequestMapping("/foo")
public String foo() {
throw new IllegalArgumentException();
}
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Specific handler", HttpStatus.BAD_REQUEST);
}
}
AnotherController without any method annotated with #ExceptionHandler:
#RestController
public class AnotherController {
#RequestMapping("/bar")
public String bar() {
throw new IllegalArgumentException();
}
}
A global #ControllerAdvice class:
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Global handler", HttpStatus.BAD_REQUEST);
}
}
Then if you visiting http://ip:port/foo, you will get 400 status code with Specific handler, and 400 status code with Global handler when you visit http://ip:port/bar.
I agree that the inability to map a specific #ExceptionHandler to handle only one specific method in the #RestController should be a very desirable feature.
I tried try{}catch(Exception ex){} and catch no exception. But
exception handler handles it nicely.
Since we are talking about hibernate exceptions, these exceptions are usually thrown at the commit phase of transaction. The problem here is that seems like you have transaction opened right in your controller which is considered as a bad practice.
What you should do is - open transaction in the application layer.
Controller just maps xml/json to incomming RequestDto object.
And then you call the Service to handle the business logic.
The Service(or its method) should be annotated by #Transactional.
#RestController
public class MyController {
#Autowired // but better to use constructor injection
private MyService myService;
public ResponseDto doSomething(RequestDto request) {
try {
myService.doSomething(request);
} catch (DataIntegrityViolationException ex) {
// process exception
}
}
}
#Transactional
class MyService {
public void doSomething() {
// do your processing which uses jpa/hibernate under the hood
}
}
Once you done that, the try catch will start behaving as expected on controller level.
However, I would even go further as DatabaseExeption shouldn't really go that far to controller. The alternative would be to use manual transaction inside of a service and do a try catch there.
Then in the Service layer transform database exception in a more generic exception with all necessary information for controllers to process.
And then you should catch that more generic exception (MyDatabaseAccessException) in the controller and transform as you wish for the sake of a presentation layer.
===
The #ControllerAdvice suggested here is good for a global exception handling across controllers.
The #ExceptionHandler is not suitable for each method unless you wnat to have controller per method. And even after that it can clash with global #ControllerAdvice.
I am not sure why spring doesn't allow #ExceptionHandler at a method level, it would simplify a lot of cases like yours.
My solution is to annotate a method with a marker:
#ExceptionHandler(SomeException.class)
public ResponseEntity<String> handleSomeException(SomeException e, HandlerMethod handlerMethod) {
var marker = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getMethod(), MarkerAnnotation.class);
if (marker != null) return something();
else return somethingElse();
}

Categories

Resources