I have an @ExceptionHandler annotated method in a @ControllerAdvice annotated class.
This method must catch all exceptions, but after some default handlers have handled some exceptions, not as first handler (for example, it should not handle org.springframework.security.access.AccessDeniedException, otherwise the forwarding to the login page, which is done by Spring, does not work anymore).
I've found a lot of stuff but either old (not using @ControllerAdvice) or with Interfaces that cannot be used, because both html and JSON must fit to the return type of the method signature (using the class ResponseEntity, not some ModelAndView or String).
My current exception handler test method, which works fine:
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleExceptions(Exception ex, HttpServletRequest request) throws Exception {
HttpHeaders headers = new HttpHeaders();
//sort MIME types from accept header field
String accept = request.getHeader("accept");
if(accept != null) {
String[] mimes = accept.split(",");
//sort most quality first
Arrays.sort(mimes, new MimeQualityComparator());
//if json, return as json
String firstMime = mimes[0].split(";")[0];
if (firstMime.equals("application/json")) {
ExceptionWrapper exceptionVO = new ExceptionWrapper(ex);
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<ExceptionWrapper>(exceptionVO, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//if not json, return as html
headers.setContentType(MediaType.TEXT_HTML);
String error = "<h1>Internal Server Error 500</h1><br>";
error += "Please copy the following text and send it to your server admin:<br><br>";
error += "<pre>" + ExceptionUtils.getStackTrace(ex) + "</pre>";
return new ResponseEntity<String>(error, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
It basically just decides in which format to return the error.
How can i lower the priority of this exception handler while still maintaining the Spring default exception handlers? Do i need to add some fancy Java-Config?
I already tried to create a class which implements ResponseEntityExceptionHandler and have overridden the handleExceptionInternal method there, which did not work. Spring complained it could not find a HttpStatus object to pass into the overridden method (ive tried providing that as bean, too).
I also tried using @Order on my @ControllerAdvice which changed nothing.
Spring Version 4.0.9
Aucun commentaire:
Enregistrer un commentaire