简体   繁体   中英

Optimize Spring RestControllerAdvice with multiple exceptions

I have around 20 to 30 different types of different Exceptions all extending Exception class in Java. one example is:

public class NoHandlerFoundException extends Exception {

private static final long serialVersionUID = -9079454849611061074L;

public NoHandlerFoundException() {
    super();
}

public NoHandlerFoundException(final String message) {
    super(message);
}

}

Other example is:

public class ResourceNotFoundException extends Exception{

private static final long serialVersionUID = -9079454849611061074L;

public ResourceNotFoundException() {
    super();
}

public ResourceNotFoundException(final String message) {
    super(message);
}

}

and many more. As you can see most of the code is repeated and then I use ControllerAdvice like (I know code in ControllerAdvice argument exception class should be proper):

@ExceptionHandler({NoHandlerFoundException.class, ResourceNotFoundException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody ExceptionResponse handleResourceNotFound(final NoHandlerFoundException exception,
        final HttpServletRequest request) {

    ExceptionResponse error = new ExceptionResponse();
    error.setErrorMessage(exception.getMessage());
    error.callerURL(request.getRequestURI());

    return error;
}

So I want to know if we have any way in which I can optimize above exceptions and not write individual classes doing almost same job n times of times but still want to differentiate between them. Thank you.

You can use below approach to reduce code redundancy.

    @ExceptionHandler(value = {NoHandlerFoundException.class, ResourceNotFoundException.class})
protected ResponseEntity handleInvalidDataException(RuntimeException exception, WebRequest request) {

    ExceptionResponse error = new ExceptionResponse();
    error.setErrorMessage(exception.getMessage());
    error.callerURL(request.getRequestURI());

    return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM