Library for providing exception handling for spring based REST APIs
This lib aims at providing extension to ResponseEntityExceptionHandler
and handle all 4xx as well as 500 exception.
spring bound provide a simple exception handling for user exceptions(4xx). Here is the defined Exception classes for most used USER Errors.
HTTP ERROR CODE | STATUS | EXCEPTION CLASS |
---|---|---|
400 | BAD REQUEST | BadRequestException |
401 | UNAUTHORIZED | UnauthorizedException |
403 | FORBIDDEN | ForbiddenException |
404 | NOT FOUND | DataNotFoundException |
500 | INTERNAL_SERVER_ERROR | SystemException |
{
"errorMessage": "Internal Sever Error : Please Try later[Refer logs for details]",
"category": "Internal Server Error",
"httpErrorCode": 500,
"transactionId": "9779f2387e8f3143",
"timestamp": "2022-10-04T16:10:09.345+00:00"
}
Above is the Exception Message generated by spring-rebound.
- Add spring-rebound dependency
<dependency>
<groupId>com.coderhop</groupId>
<artifactId>spring-rebound</artifactId>
<version>1.0.7</version>
</dependency>
- Make sure that
com.coderhop
(along with your base package) is added inComponentScan
in order to add exception handling classes.
@ComponentScan("<project base package>,com.coderhop")
-
As required throw these exception from services/other API classes like below
throw new com.coderhop.rebound.exception.model.DataNotFoundException("No Data found for Id: 0001 "); //other example //throw new com.coderhop.rebound.exception.model.BadRequestException("Invalid Request : Employee Id cant be null"); //throw new com.coderhop.rebound.exception.model.SystemException("Processing Logic Failed due to connection Failure");
Here is the exception message generated for DataNotFoundException
{ "errorMessage": "No Data found for Id: 0001 ", "category": "Not Found", "httpErrorCode": 404, "transactionId": "3fbad17306c97c6e", "timestamp": "2022-10-05T03:00:33.489+00:00" }
-
spring-rebound piggy-back on distributed tracing library sleuth for determining transactionId . The idea is return the log correlation id as exception response in order to ease out debugging. In case application is not using sleuth it will return http request sessionId as transactionId value.
below is log for an app which uses sleuth and transactionId can be found as trace/spanId in log statements .
[2m2022-10-04 23:00:28.098 INFO [,,] 46036 --- [ main] com.demo.DemoApplication : Started DemoApplication in 3.276 seconds (JVM running for 3.99) 2022-10-04 23:00:33.464 INFO [,3fbad17306c97c6e,3fbad17306c97c6e] 46036 --- [nio-8082-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2022-10-04 23:00:33.465 INFO [,3fbad17306c97c6e,3fbad17306c97c6e] 46036 --- [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2022-10-04 23:00:33.467 INFO [,3fbad17306c97c6e,3fbad17306c97c6e] 46036 --- [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms