简体   繁体   中英

Parsing JSON by jackson

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM