Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST URL error handling using the Play framework

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?

like image 812
CQM Avatar asked Jun 07 '11 20:06

CQM


People also ask

What is a REST API for Play Framework?

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.

What happens if the user misspells the URL of REST API?

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.

How do I handle an HTTP error in resttemplate?

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.

How to store student records in Play Framework?

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.


1 Answers

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.

like image 171
pickypg Avatar answered Sep 30 '22 09:09

pickypg