I have a form where the parameters packed in JSON are parsed by Jackson. If the parameter type is 'int' and the user inputs a big number, I have an exception. I restrict doing that on clientside, but want to know, what is the best practice in dealing such type of exceptions? Should I bother? Or it's just ok?
-
As long as the input is coming only from the client side, having a validation on the client side should be OK. If the input can also come from other sources, having a check in the parsing method is advisable. Doesn't Jackson support BigInteger? – Dakshinamurthy Karra Jun 22 '15 at 07:19
1 Answers
Always include server-side validation
Since client-side validation can be easily avoided by manually sending a request to an endpoint (in PostMan or using DevTools for example), you are right to encourage validation on both client and server-side. Especially if you want to open up an API publicly, server-side validation is essential. You can not trust every client that interacts with your API. Here are a couple of pointers:
Return response status of 422 Unprocessable Entity
Assuming you are using HTTP for communication, the appropriate response code to return is 422. 422 represents a validation error and there is a quality explanation here. It is more RESTful/HTTP-compliant to return a descriptive status code for different error scenarios. For this example, you provide your clients with more information by returning a 422 compared to a 500. You could go even further by returning an error response that describes the field that is invalid.
Use JAX-RS to map exceptions to responses
JAX-RS is a specification that makes it easy to build RESTful web services in Java. If you have a JAX-RS implementation already wired up in your application, you can define an exception mapper to look for JsonMappingException
, check for a cause of NumberFormatException
(if you are using boxed Integer
) and return the appropriate response when that case hits.
-
1I would vote for code 400 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400). Code 422 would indicate that "that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions." (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422). The syntax is not as expected and thus the server can not process the request. Apart from that I'm fully agreeing with your post :) – Aaron Dietz Feb 15 '22 at 08:27
-
@AaronDietz I've learned a lot and changed my opinions quite a bit since writing this post. 7 years in tech is like 1000! Haha. In practice I would use a 400 now too. In general I try to keep my APIs simpler, I've moved away from trying to be hardcore "REST", which at this time I was really excited about. I like simplicity, I agree, I think 400 covers the case just fine. – Sam Berry Feb 15 '22 at 17:38