Master your API: Exception Handler with RFC 9457
Who has never seen an API that returns 200 (ok) with an error message, or maybe a different format of message errors for each endpoint?
Well, if this is your case, I hope this article can guide you to handle unexpected situations and errors gracefully.
RFC 9457
RFC 9457 introduces a standardized way to handle errors in HTTP APIs by defining the "Problem Details" for HTTP APIs. This specification outlines a format for error responses, ensuring consistency and clarity. Key elements of RFC 9457 include:
Type: A URI reference that identifies the problem type.
Title: A short, human-readable summary of the problem type.
Status: The HTTP status code generated by the origin server for this occurrence of the problem.
Detail: A human-readable explanation specific to this occurrence of the problem.
Instance: A URI reference that identifies the particular occurrence of the problem.
Example with Spring
Spring supports RFC 9457, and we can do it by creating a class that has the annotation @ControllerAdvice.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<ProblemDetail> handleResourceNotFoundException(EntityNotFoundException ex, WebRequest request) {
ProblemDetail problem = ProblemDetail
.forStatusAndDetail(HttpStatus.NOT_FOUND, "Resource Not Found");
return new ResponseEntity<>(problem, HttpStatus.NOT_FOUND);
}
}
Conclusion
Exception handling is crucial for creating robust, user-friendly, and secure REST APIs. By adopting a standardized approach like the Problem Details format from RFC 9457, developers can ensure that their APIs provide consistent and meaningful error responses.
Implementing a global exception handler, along with specific handlers for different types of exceptions, helps maintain the stability and reliability of the API while enhancing the user experience.
Did you already know this RFC? If you want to know more about REST and best practices, please subscribe.