Custom error messages for Jersey/JAXB XML validation errors - jaxb

So I have a REST service setup with Jersey.
My POJO is simply annotated as #XmlRootElement
I send a POST request to my REST service and everything works fine.
1- I send malformed XML to the service I get back the containers default 400 Bad Request page. Using Glassfish 3 I can't remember exactly but I know I can change or tell my web app to map to my own 400 bad request right? Where can I look for docs on that specific subject.
2- I send valid XML but in one of the expected fields I put empty value. My service tries to do something and it throws a persistence exception. I get back the containers default 500 Internal Server Error page and it list the exception thrown. I guess I can map to my own custom error page as well, but I do not just want to show the exception message. This is considered a security issue.
I would basically like to validate the fields myself based on my business logic and return back to the client an error message such as "Field1 is invalid" Nothing more nothing less. And the client should be able to parse the error code and also know which field was wrong.
Also what can I do when my service has more then one type of bad request error? For instance, the field can expect an INT value between 1-3, but specific business request expects value of 2 and a 3 is sent.
So for type/value validation I want to simply say "Invalid field name here". But for specific business logic say for instance "Invalid account" or "Account Expired" or "Address Does Not Match" etc...
Or how about when I have more then 1 success code?
Basically I'm taking an old "xml" type service and converting to REST style for proof of concept and bring it up to standards. The old one pretty much is 100% POST even when "querying for results. I.e: GET. So basically you POST to it XML, it reads the XML, calls the business logic and logic returns appropriate code in the XML response. So everything is HTTP 200 OK and the business logic code is returned in an XML response. So the only time a client gets a 500 error is when there is hard failure where the service can't produce an XML response. Even invalid XML is returned as 200 OK, but the XML response back indicates this with my own errors codes.
A while back I was suggested I use SOAP for more "message" oriented services, but I still think it's to heavy and I can achieve with REST what my service does, even though I don't need most of REST?

You can map exceptions to HTTP responses using ExceptionMappers - see:
http://jersey.java.net/nonav/documentation/1.11/jax-rs.html#d4e433
http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/ext/ExceptionMapper.html
If you want to do validation before the request even reaches the resource method, you can try writing a ContainerRequestFilter for that and throw a WebApplicationException which takes Response as a parameter - jersey automatically maps that exception to the response it was initialized with.

Related

NodeJS - Is it OK to call db insert/update functions without await?

I have a backend application and there are insert/update endpoints. They mostly go as:
Check and validate the input
Submit the input to db
Return status 200/201 with location header set and body contains status message
Would it be ok to make the 2nd step without await so that response can be returned faster? The returned status will be set to 202, which means it is currently processing. The possibility of 2nd step to throw error is extremely low, or if it does there is a bug going on somewhere and does not relate to the end-user anyways, hence no need to return such error to user.
Would this work? Even if this works, would it be a good practice?
It's OK to not wait for the database response to succeed before doing other things (like sending back a response) if that's how you want your app to work and you're sure that's the right design and you've thought through what happens (from the end user's point of view) if that database call (that you didn't wait for) fails.
BUT, it's not OK to ignore a rejected promise that might come back from the database call because unhandled promise rejections should not happen in a nodejs server. So, if you're not going to use an await, then you probably need a .catch() to catch and at least log the error.
Would this work?
Yes. There's nothing in the language or in nodejs stopping your from sending a response before the database call has completed. It's more about whether that's the appropriate way to design your response handler.
Even if this works, would it be a good practice?
It's not a widely recommended practice because the usual sequence is this:
Check and validate the input
Submit the input to db
If success, return status 200/201 with location header set and body contains status message
If error, return appropriate error status (based on type of error) and status message.
I'm not saying that you can never deviate from this sequence, but doing so would generally be the exception, not the rule.
Keep in mind that data validation does not necessarily catch everything that might cause the database to generate an error. For example, you could be creating a new user on your site and the email address is perfect valid in validation, but then the database rejects it because it's not unique (there's already a user with that email address).
And, the database itself could be having problems, causing an error and the user should be informed that the transaction they were trying to submit to the database did not happen event though the error was not directly caused by the user.

Serving a HTTP request response as a dialog response - Composer Framework

We are developing a chatbot to handle internal and external processes for a local authority. We are trying to display contact information for a particular service from our api endpoint. The HTTP request is successful and delivers, in part, exactly what we want but there's still some unnecessary noise we can't exclude.
We specifically just want the text out of the response ("Response").
Logically, it was thought all we need to do is drill down into ${dialog.api_response.content.Response} but that fails the HTTP request and ${x.content} returns successful but includes Tags, response and the fields within 1.
Is there something simple we've missed using composer to access what we're after or do we need to change the way our endpoint is responding 2? Unfortunately the MS documentation for FrwrkComp is lacking to say the very least.
n.b. The response is currently set up as a (syntactically) SSML response, this is just a test case using an existing resource.
Response in the Emulator
Snippet from FwrkComp
Turns out it was the first thing I tried just syntactically correct. For the case of the code given it was as simple as:
${dialog.api_response.content[0].Response}

Is ending responses in Express with a status code always necessary or recommended?

I'm confused about this. I have seen a lot of people ending responses with just res.send();. At the same time, some tend to include a status code, like res.status(422).send();. I understand that this is useful when a user, for example, has sent a request to /log-in/ with data that represents a type different from the one needed and appropriate. In such cases, I'm ending my responses with res.status(422).send();. If I'm expecting a username, but I instead receive an array, it seems to me that such an approach is appropriate. However, if everything is technically alright and the user has just entered a username that does not exist, do I need to include a status code? When such a thing happens, a message under the form will be displayed instead. And res.send("This username does not exist."); is the function I would call. Should I call res.status(401).send("This username does not exist."); instead?
Technically you are not forced to use status codes however it's recommended to follow the best practices.
When the user does not exist return 404 not 401. 401 is unauthorized
When user input is not expected, that's validation error(bad request) and return 400 instead of 422. 422 is used in slightly different scenarios.
Read more about it 400 vs 422
More details about http status codes
Yes, status codes are very important as a good practice I would prefer 404 instead of 401 in your case res.status(404).send("This username does not exist.");
stackOverflowAnswer
Why do we use the status code?
To make your debug life easy/ better error handling and to log the error in production to know the severity of the error your application has in case it crashes.
How to Specify statusCode in Node.js
When to use what status code
By default, Express answer all endpoints with 200 unless you didn't specified an endpoint, in this case it will automatically reply with 404.
by the way, Express also has res.sendStatus() function that ends the request and sending status
This has to do with your api design. Generally you would be publishing your api specs (Api specification) and there would mention how your client can find out if something is going wrong or going fine.
HTTP Response code are some of easiest way to inform client about outcome of request. So they don't have to go inside the payload of response to check what was outcome. Since most of codes are well know and there is consensus you will write more standard code which works with network elements like proxies, load-balancer etc and understandable developers.
Advantages of status codes

JMeter - API test Plan - Service unavailable. Please try again later error

I created an API test plan in JMeter.
(Post) Login Authentication API
(Get) API to search for data (Authenticated with the help of correlation)
The Login API works fine I am able to see the response. But, the Search API is returning an error "Service unavailable. Please try again later." with error code 500. My API request has got all the data required Can someone help me to fix the issue.
Thanks,
As per 500 Internal Server Error description:
The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
This error response is a generic "catch-all" response. Usually, this indicates the server cannot find a better 5xx error code to response. Sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future.
So my expectation is that you should rather check your server logs to figure out the root cause of the problem rather than looking for a solution from JMeter side.
In general if something is wrong with your request the server should respond with 4xx status code
If you have another way of sending the "search" request you can inspect it and cross check all the associated data including:
URL
Headers (can be passed via HTTP Header Manager), pay attention to Content-Type one
Request body
The value you correlated which can be checked using Debug Sampler and View Results Tree listener combination

Supporting Server side validation with ServiceStack.Razor

I have a Service which, depending on content type, either uses Razor to return HTML or returns JSON. When in HTML mode I want to support server side (non-JavaScript) validation of Forms. I wish to rely on the repository for validation, if the repo returns an error I re-display the form along with the error message from the repo.
The model I am using is this:
in json mode simply throw an Exception
in HTML mode return a response containing both the partially created object and the response status.
This allows me to re-display the form using the same View that I would use when editing an existing object and also display the error message contained in Model.ResponseStatus.Message.
My question: Does anyone have any thoughts on how well I am using the facilities provided by ServiceStack? Is there a better, cleaner, simpler way?

Resources