Exception Processing @RestControllerAdvice in Spring

A very useful class in the Spring 4 plus is the  @RestControllerAdvice, it combines the @ControllerAdvice inside. By defining a @RestControllerAdvice, when a controller thorw one exception, you can put all the exception handlers code into one class and you then can choose to use different @ExceptionHandler method to deal with different exceptions , or you even can deal all in one method to use the instance check up to decide what response msg you should send out in response;

So you have chance to reply user a friend msg of your runtime exception of your Restful API, and even with customized http status code too with ResponseEntity class.

Here I put a fake sample code to show how it works. you can do more study and use the handler in your way. Result is a class you defined Object your want to reply to client side.


@RestControllerAdvice
public class GlobalExceptionHandler {

private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(value = { MyCustomizedException.class })
 @ResponseStatus(HttpStatus.BAD_REQUEST)
public Result myCustomizedExceptionHandler(MyCustomizedException ex) {
 // ..... what ever process
 return new Result(500, 0001, ex.getMessage());
 }


@SuppressWarnings("rawtypes")
 @ExceptionHandler(value = Exception.class)
 public ResponseEntity handle(Exception e) {
 e.printStackTrace();
 Result rt = new Result(e.getMessage());

if (e instanceof SoaException) {
 rt = ((SoaException) e).getBodyStatus();
 } else if (e instanceof MissingServletRequestParameterException) {
 rt = DataUtil.rt("0002");
 } else if (e instanceof HttpRequestMethodNotSupportedException) {
 rt = DataUtil.rt("0003");
 } else if (e instanceof HttpMediaTypeNotSupportedException) {
 rt = DataUtil.rt("0004");
 } else if (e instanceof HttpMessageNotReadableException) {
 rt = DataUtil.rt("0005");
 } else if (e instanceof BindException) {
 rt = DataUtil.rt("0006");
 } else if (e instanceof NumberFormatException) {
 rt = DataUtil.rt("0007");
 } else if (e instanceof DataIntegrityViolationException) {
 rt = DataUtil.rt("0008");
 } else {
 rt = DataUtil.rt(Constants.ERROR_CODE);
 }
 LOGGER.error(rt.getMessage() + e);
 return new ResponseEntity<>(rt, HttpStatus.OK);
 }

 

Advertisements