Currently when I (or more importantly, a user) type in one of my rest functions into the URL, it works, with the 200 status code. But if you type a wrong one or mispell it, a 404 page is generated, with a 404 status code when looking at it through a REST client.
Instead of getting a 404 page when the bad URL is sent, I would instead like to display a dynamically generated JSON object.
How do I fix that error handling to do what I want, Is there a place where I can define what should be done during a particular status code?
The purpose of this tutorial is to explore the Play Framework and learn how to build REST services with it using Java. We'll put together a REST API to create, retrieve, update, and delete student records. In such applications, we would normally have a database to store student records.
It is understandable that for the user it is easier to check the status code of 404 without any parsing work to do. We did reach the REST API, we did got response from the REST API, what happens if the users misspells the URL of the REST API – he will get the 404 status but that is returned not by the REST API itself.
By default, the RestTemplate will throw one of these exceptions in case of an HTTP error: All these exceptions are extensions of RestClientResponseException. Obviously, the simplest strategy to add a custom error handling is to wrap the call in a try/catch block.
In such applications, we would normally have a database to store student records. The Play Framework has a built-in H2 database, along with support for JPA with Hibernate and other persistence frameworks. However, to keep things simple and focus on the most important stuff, we will use a simple map to store student objects with unique IDs.
I am not very familiar with the Play Framework, but I was interested. This discussion seemed at least similar to what you want:
Gaëtan Renaudeau
...
You can customize errors pages depending of the http code error (404, 500, 403, ...) by editing app/views/errors/{code}.html files where {code} is you http code. If you are using other format than html (like xml, json) you can have 404.json , 404.xml, etc...
So, modify:
app/views/errors/404.type_of_response
Hopefully this at least points you in the right direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With