Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC - @ExceptionHandler based on Accept header

I have a HandlerInterceptorAdapter that intercepts all requests and performs user authorization checks. Very basically:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    User user = ... // get user
    checkIfAuthorized(user); // throws AuthorizationException
    return true;
}

I then have an @ExceptionHandler for that AuthorizationException.

@ExceptionHandler(value = AuthorizationException.class) 
public ResponseEntity<String> handleNotAuthorized(AuthorizationException e) {
    // TODO Custom EXCEPTION HANDLER for json/jsp/xml/other types, based on content type
    ResponseEntity<String> responseEntity = new ResponseEntity<>("You are not authorized to access that page.", HttpStatus.UNAUTHORIZED);
    return responseEntity;
}

This is fine if the (unauthorized) request accepts text/plain (and can be easily changed for json). How can I make different @ExceptionHandlers for specific Accept headers?

@RequestMapping has produces(). Is there something similar for @ExceptionHandler?

like image 256
Sotirios Delimanolis Avatar asked Jun 26 '13 14:06

Sotirios Delimanolis


1 Answers

I know this comes late but I've been looking up a solution to this, came across this question and found what I think to be a better solution. You can return "forward:/error" in your @ExceptionHandler (returning a String) to forward the request to a

@RequestMapping("/error")
ErrorController {...}

and use

@RequestMapping(produces = "text/html") 
ModelAndView errorPage() {...}

on one method of that ErrorController,

@RequestMapping(produces = "application/json") // or no 'produces' attribute for a default
MyJsonObject errorJson() {...} on another.

I think this is a pretty neat way to do it, it's probably already out there but I didn't find it when trying to look it up.

So basically the @ExceptionHandler is the same for all, but forwards to a controller that can do the usual stuff

like image 174
A D Avatar answered Oct 02 '22 23:10

A D