Jersey/Jackson: how to catch json mapping exception?(Jersey/Jackson:如何捕获 json 映射异常?)
问题描述
我想在我的 restful 服务中捕获 json 映射异常,以防输入 json 无效.
I would like to catch json mapping exception in my restful service in case input json is not valid.
它抛出 org.codehaus.jackson.map.JsonMappingException
,但我不知道如何或在哪里捕获此异常.我想捕获这个异常并发送回适当的错误响应.
It throws org.codehaus.jackson.map.JsonMappingException
, but I don't how to or where to catch this exception. I want to catch this exception and send back appropriate error response.
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"name",
"id"
})
public class Customer {
@JsonProperty("name")
private String name;
@JsonProperty("id")
private String id;
<setter/getter code>
}
public class MyService {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public final Response createCustomer(@Context HttpHeaders headers,
Customer customer) {
System.out.println("Customer data: " + customer.toString());
return Response.ok("customer created").build();
}
}
一切正常,但如果 json 主体格式不正确,则会引发 JsonMappingException
异常.我想捕捉这个异常.
Everything works fine, but if json body is not well formed then it throws JsonMappingException
exception. I want to catch this exception.
推荐答案
最终对我有用的是为 JsonMappingException
声明一个 ExceptionMapper
提供程序,例如
What finally worked for me was to declare an ExceptionMapper
provider for JsonMappingException
, such as
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.stereotype.Component;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Component
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
这篇关于Jersey/Jackson:如何捕获 json 映射异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jersey/Jackson:如何捕获 json 映射异常?
基础教程推荐
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01