Mapping errors with values in Jersey - rest

I have a REST application implemented using Jersey JAX-RS. I have to make a mapping between some errors and values.
Something like this:
400 - Bad Request -> The request contained invalid data (e.g. missing, wrong parameter values)
404 - Not Found -> Invalid URL
How do I specify to the application how to associate an error code with a particular exception/error?

You can do something like :
try{
....
}catch(...){
return Response.status(Status.NOT_FOUND);
}
were Response is package javax.ws.rs.core.Response

you can use the exception mapping feature
javax.ws.rs.ext.ExceptionMapper;
I have sample here, use full content to refer
LetzRestOnJersey

Related

RestTemplate considering a resource to be a parameter

My request goes like this... https://......./results/#codeResults
When i hit this get request with postman, i get the desired output. (Please note that #codeResults is used as it is in the request and is not to be replaced by any value)
But when I try to hit this using exchange method of RestTemplate it says -
Status Code : 400
message: invalid resultId: #codeResults
As an alternative approach, I tried to pass #codeResults as a path param using URIComponentBuilder as well but still I am getting the same issue.
Please provide any pointers on this.

How do you post to a Web API 2 OData Controller

I created a Web API 2 project and configured an OData4 controller following the steps here: Web API 2 Odata 4 Tutorial
However whenever I try and do a simple POST(with a JSON body to create an entity) using Postman I get the following error back:
The requested resource does not support http method 'POST'.
The POST action in the controller looks like this:
public async Task<IHttpActionResult> Post(Product product)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
The JSON I am posting in the request body is as follows:
{
"Id":"lewisblack",
"Name":"Lewis",
"Price":"Black",
"Category":"Category 1"
}
And I included the following headers in the request as well:
OData-Version: 4.0
OData-MaxVersion: 4.0
Content-Type: application/json
Am I missing something here?
UPDATE: Figured out the issue. I was using an incorrect URI.
Not much information to go on:
I suspect you don't have a PostMethod on the related controller.
Otherwhise, some other things to think about:
OData is case sensitive
You are missing a property that is required
a datatype is wrong ( Id in the example project is an integer, it looks like a string in your project, Price should be a decimal and not a string, ...)
Whats the HTTP Response code ( if above didn't help), when you post the object. ( use a tool like fiddler). Tip, if your http response is a "bad request", then your data is probably invalid to continue in the action.
I incorrectly used http://localhost:/ for the POST instead of https://localhost:/Products

HTTP reponse for error in REST call for Mojolicious

The mojolicious application that I use is JSON based, that is the interaction between the client and the server is more of an exchange of JSON structured data.
I am trying to implement a standard way of handling errors with proper HTTP response code when an error occurs during one of the REST calls. What is the best way of implementing such a standard and where do I do it?
I see a couple of ways of doing it
Create a class and list all the error response and its associated content, a call could be made to this class with the response code, which would return the JSON structure(combination of hashes and arrays) containing all the associated entry, then use the render_json() method in controller and return this as a response to the client
I can create a table in the Database with entry for all the fields that are required for the response, use the filed to access the JSONstructure, create the appropriate response and use render_json() in controller and return this as a response to the client.
Example of error response might be like
{
"Message": "The requested resource is not found"
"Type" : "http://this.is.an.error.com/error/resource_not_found",
"ErrorCode" : 404,
"Created" : "2012-11-05T11:59:29-05:00",
"Request" : "GET /types/Foo/instances"
}
What is the right way of standardizing such a response?
As titanofold mentioned, I'd go for option 2.
Regarding error codes, try to stick with standard HTTP Response Status Codes.
Besides setting the ErrorCode property in your JSON, you should send the status code in the response header because:
you can treat errors in a single place - the error callback of your javascript function
in the future you might have other consumers of your backend (mobile apps for example)
this is why they have been invented
You can achieve that extremely simple with Mojolicious:
$self->render_json( {
Message => "The requested resource is not found",
Type => "http://this.is.an.error.com/error/resource_not_found",
ErrorCode => 404,
Created => "2012-11-05T11:59:29-05:00",
Request => "GET /types/Foo/instances",
},
status => 404);
The wonderful things about standards are that there are so many to choose from, and if you don't like any of them you can make your own.
As to the REST structure, that's up to you. I would go for the generic 'code' rather than 'ErrorCode' as you should return a code on success, too.
For your method options, I'd go with option 2.
I would also opt for option 2. But I do not understand the need for the error details to be part of the database. I would rather suggest you use a the OO concept of base class holding all the error details and the inheriting it to other classes, making sure you have access to it.

Url as path parameter in restful api causes bad request

We are developing a restful api using jersey (1.9.1) and tomcat 5.5.
A given resource is identified with a urn and we would like to address a specific instance of that resource. In order to achieve this, we used the following code:
#Path("/XXXs")
public interface XXXResource {
#GET
#Path("{id}")
#Produces({ MediaType.APPLICATION_JSON })
XXXInfo getXXX(#PathParam("id") String id);
}
The idea is to address this resource using the following url:
http://localhost:8080/restapi/XXXs/http%3A%2F%2Fns.something.com%2FXXX%2F2
The decoded path param value should be:
http://ns.something.com/XXX/2
However, when I make the request using the encoded url I get a bad request message from tomcat. So my questions are:
Is it correct to use a Urn as a path parameter?
Why is tomcat considering this request as a bad request?
Just in case, I changed the signature of the method so that the parameter is taken from the query string and it worked fine, but I want the parameter to be part of the path.
Thanks.
Ok, I solved it by adding the following line in catalina.properties:
org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true

JSON endpoint with .NET RIA Domainservice

I have created a RIA-service and added a JSON endpoint following this tutorial: http://www.c-sharpcorner.com/UploadFile/pchandraker/1320/. When testing it in the browser, hitting
http://localhost:52878/Project-Web-DomainService.svc/json/GetProjects
returns nothing. When inspecting the request in Firebug, neither the response headers or body is set. Hitting an invalid url, such as http://localhost:52878/Project-Web-DomainService.svc/json/GetProjectsINVALID returns a 404, saying "Endpoint not found" as expected.
Do I need to add additional metadata or configuration settings to either DomainService.cs or Web.config to get the JSON output?
Decorate your GetProjects functions from DomainService with [QueryAttribute(HasSideEffects = true)] attribute.
Good luck.