I have this code where I'm supposed to return a customized error message and error code. It works fine but the problem is that it's extremely redundant. I was wondering if it's possible to handle all these custom exceptions with one @ExceptionHandler.
@ControllerAdvice
public class HandleExceptions {
@ExceptionHandler(value = CustomException1.class)
public ResponseEntity<Object> handleCustomException1(CustomException1 e) {
HttpStatus status = HttpStatus.NOT_FOUND;
DataResponse data = new DataResponse("custom status code for exception 1", e.getMessage());
ExceptionResponse exceptionResponse = new ExceptionResponse(data);
return new ResponseEntity<>(ExceptionResponse, status);
}
@ExceptionHandler(value = CustomException2.class)
public ResponseEntity<Object> handleCustomException2(CustomException2 e) {
HttpStatus status = HttpStatus.NOT_FOUND;
DataResponse data = new DataResponse("custom status code for exception 2", e.getMessage());
ExceptionResponse exceptionResponse = new ExceptionResponse(data);
return new ResponseEntity<>(ExceptionResponse, status);
}
@ExceptionHandler(value = CustomException3.class)
public ResponseEntity<Object> handleCustomException3(CustomException3 e) {
HttpStatus status = HttpStatus.BAD_REQUEST;
DataResponse data = new DataResponse("custom status code for exception 3", e.getMessage());
ExceptionResponse exceptionResponse = new ExceptionResponse(data);
return new ResponseEntity<>(ExceptionResponse, status);
}
public class ExceptionResponse {
private final DataResponse data;
}
public class DataResponse {
private String statusCode;
private String message;
}
The custom error classes all look like this:
public class CustomException extends RuntimeException{
public CustomException(String message){
super(message);
}
}
An example of the response would be:
Data: {
status: 1111,
message: user not found
}
You can create a single method that takes a generic
RuntimeExceptionas the parameter and use anif/elsestatement to check the type of the exception and modify the response accordingly.The below method checks the type of the exception and sets the appropriate HTTP status code and error message in the DataResponse object. If the exception is not one of the custom exceptions, a generic error message and status code is returned.