Δευτέρα 2 Δεκεμβρίου 2024

Exception handling with Spring Boot

 EXCEPTION HANDLING WITH SPRING BOOT



1. Use @ResponseStatus for simple cases




When ResourceNotFoundException get thrown, client will get a 404 status code.



2. Use @ControllerAdvice for Centralized Exception Handling



  • @ControllerAdvice handler intercepts exceptions thrown from any controller.
  • With ResponseEntity, we can return custom error messages, objects, HTTP status codes and response bodies.



3. ErrorResponse custom pojo class


     Moreover, we can define an ErrorResponse custom pojo model to include in                         ResponseEntity:






4. Include validation errors in ResponseEntity




    We can stream all errors gathered, into an ErrorResponse's errorMessage string value.




5. Map custom exceptions to error codes for API integrity




In our CustomBusinessException we link a specific Error Code (e.g. ERROR_1)
Then, we add it in ErrorResponse and to ResponseEntity.

That way, clients that consume our API will have a clear matching between our backend errors and an identifying reason (error code)





Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?