Long time I couldn't have time to write in my blog. So this time I am going to talk about spring boot exception handling with error code mapping. This blog post helpful to who are new to spring boot. The first thing is define error codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public enum ApiError { INVALID_REQUEST_PARAMETERS("E10001", "Invalid request parameters"), PRODUCT_NOT_FOUND("E1001", "Product not found"); private final String errorCode; private final String errorMessage; ApiError(String errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } public String getErrorMessage() { return errorMessage; } } |
The next task is write runtime exception type based on HTTP status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import io.apptizer.api.errors.codes.ApiError; public class ResourceNotFoundException extends RuntimeException { private ApiError apiErrors; public ResourceNotFoundException(ApiError apiErrors, String message) { super(message); this.apiErrors = apiErrors; } public ApiErrors getApiErrors() { return apiErrors; } public void setApiErrors(ApiErrors apiErrors) { this.apiErrors = apiErrors; } } |
And final task is write exception mapper handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionMapperHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorInfo> resourceNotFound(ResourceNotFoundException ex) { ErrorInfo errorInfo = new ErrorInfo(ex.getApiErrors().getErrorCode(), ex.getMessage()); return new ResponseEntity<>(errorInfo, HttpStatus.NOT_FOUND); } } |
then in your rest service you can throw exception with error code mapping.
throw new ResourceNotFoundException(ApiError.PRODUCT_NOT_FOUND, "Product Task Not Found");
And that is it.If you have any better way please put your comments.
No comments:
Post a Comment