Does anyone know the best/simplest way to use @ExceptionHandler
for wrapped Exceptions?
I have a custom org.springframework.core.convert.converter.Converter
that I use for converting a @PathVariable
and it throws a custom runtime exception if the input is outside a standard range.
This winds up being wrapped in a ConversionException
by Spring, which I can handle with @ExceptionHandler(ConversionException.class)
in my Controller Advice.
However I have to .getCause()
and use instanceof
to determine if the underlying exception is the type I'm interested in. At that point I can use the response to .sendError()
but in the case where I have a different underlying exception I'm not sure what to do?
If I rethrow the original exception I get a nasty log message 'Failed to invoke @ExceptionHandler method', and it doesn't feel right.
Is there an easy way to do something like @ExceptionHandler(MyCustomConversionException.class
) where MyCustomConversionException
is the cause of the ConversionException
in the @ControllerAdvice
?
Thanks!
Create a ControllerAdvice class @ControllerAdvice
which would allow you to create multiple @ExceptionHandler
entries. Each method can reference a single exception or multiple exceptions.
for example:
@ControllerAdvice
public class ExceptionController extends ResponseExceptionHanlder {
@ExceptionHandler(value = { NumberFormatException.class })
protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
//TODO: Handle exception
return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(value = { InvalidClassException.class })
protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
//TODO: Handle exception
return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(value = { MaxUploadSizeExceededException.class, SizeLimitExceededException.class })
protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
//TODO: Handle exception
return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.