More Related Content

Using jersey exception mapper

  1. By Anirban Sen Chowdhary
  2. .
  3. Here I will show you how ……
  4. Let us consider we have a following Mule flow :- As you can we have exposed a REST web service in our application. Now if we test this web service it will fetch some records from Database and display in browser
  5. As you can see that we have hit the url http://localhost:8082/getData/retrieve/?id=1 on browser and getting the desired result on it
  6. Now, let’s use jersey:exception-mapper in our Mule flow to map the jersey based exception that allow mapping generic exceptions that may be thrown in the component class to HTTP response codes like the following :- <flow name="MainService" doc:name="MainService"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/> <logger message="RequestLog :- #[message.payloadAs(java.lang.String)]" level="INFO" doc:name="RequestLogger"/> <jersey:resources doc:name="REST"> <component class="com.testservices.schema.maindata.v1.Impl.MainDataImpl"/> <jersey:exception-mapper class="com.test.custom.response.NotFound" /> </jersey:resources> <logger message="ResponseLog :- #[message.payloadAs(java.lang.String)]" level="INFO" doc:name="ResponseLogger"/> </flow>
  7. That’s it…. Now our jersey:exception-mapper java class NotFound :- public class NotFound implements ExceptionMapper<NotFoundException> { public Response toResponse(NotFoundException exception){ return Response.status(Response.Status.BAD_REQUEST).entity("No Resources available at :- : " + exception.getNotFoundUri().toString()).build(); } } You can see that we can also customize the http code and can generate our custom message. Now generally if a resource is not found the http code will be 404. But we can customize the http code even this jersey:exception-mapper and we have put here http code 400
  8. Now you can see that if we pass any wrong url it is displaying our custom message that we have written in our Java :-
  9. Also you can see that we have successfully customized and changed the http status code to 400 :-
  10. Hope you enjoyed the simple yet an amazing trick in Mule