[英]How to handle error of wrong JSON data in Java Rest Web Service: Jackson JSON Parser Unrecognized token
這是我的Web服務,其中我在學生對象中接收JSON。
@PUT
@Path("/{stuId}")
@Consumes({MediaType.APPLICATION_JSON})
public Response update( @PathParam("stuId") UUID stuUUID , Student updatedStudentInfo) {
return updateService.update(stuUUID, updatedStudentInfo);
}
這是學生班:
public class Student{
private int id;
private String studentName;
private String Address;
@JsonProperty
public int getId() {
return id;
}
@JsonProperty
public void setId(int id) {
this.id = id;
}
@JsonProperty
public String getStudentName() {
return studentName;
}
.
.
.
.
}
它工作正常,但是當我通過發送錯誤的JSON數據對其進行測試時,我無法處理這種情況。 例如,如果我這樣做
curl -v'https:// localhost:9803 / school / student / 29374-345tr-44'- X PUT -H'接受:application / json,text / plain,/'-H'我的API版本:1 '-H'授權:基本'-H'內容類型:application / json; charset = utf-8'--data'{“ studentName”:“ rock”,“ Address”:723868764}'
它產生一個錯誤:
Unrecognized token '723868764': was expecting ('true', 'false' or 'null')
現在我該如何處理這種情況,即如果出現一些錯誤的數據,則除了我要發送的錯誤或異常外,它不應發回任何錯誤或異常。
編輯1:
在下面我們還可以看到由Java代碼生成的異常
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'sdfsdfdsfdsf': was expecting ('true', 'false' or 'null') at
[Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@5c6d324d; line: 1, column: 59]
我找到了兩種解決方案:
解決方案1: ExceptionMapper(球衣)
@Provider
public class ClientExceptionMapper implements ExceptionMapper<Throwable>
{
@Override
public Response toResponse(Throwable ex)
{
return Response
.status(Response.Status.BAD_REQUEST)
.build();
}
}
這里重要的是注釋
@provider
我不確定使用注解將掃描配置放入web.xml后是否有必要,但出於安全考慮,讓我們這樣做
<servlet>
<servlet-name>my-servlet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.myrootpackgae.ws;com.anotherPackage.errorHandling;
</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.scanning.recursive</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
您的ExceptionMapper類應位於Rest Service的同一包中,或位於Package層次結構下。
最后但並非最不重要的一點是,我在示例中使用了Throwable,但是您可以特定於任何Exception
JsonParseException
JsonMappingException
UnrecognizedPropertyException等...
解決方案2: javax.ws.rs.container.ContainerResponseFilter
public class MyRestAppResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
// Remove StackTrace from all exceptions
Object entity = responseContext.getEntity();
if (entity instanceof Throwable) {
responseContext.setEntity(null);
responseContext.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
// TF-246 Prevent caching for privacy reasons
responseContext.getHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
responseContext.getHeaders().add("Pragma", "no-cache");
responseContext.getHeaders().add("Expires", "Thu, 01 Jan 1970 01:00:00 CET");
// TF-752 Enable CORS for WkWebView
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
請求的事件偵聽器也是可用的RequestEventListener
,它提供了onEvent(RequestEvent)
方法。
我更喜歡使用解決方案2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.