JAX-RS jersey ExceptionMappers用户定义的异常 [英] JAX-RS jersey ExceptionMappers User-Defined Exception
问题描述
我是新手,试图阅读一些文档,但它不起作用,请耐心等待。
I am new to this, trying to achieve reading some docs but its not working, please bear with me.
我创建了一个 UserNotFoundMapper
使用 ExceptionMappers
,如下所示:
I have created a UserNotFoundMapper
using ExceptionMappers
like this:
public class UserNotFoundMapper implements ExceptionMapper<UserNotFoundException> {
@Override
public Response toResponse(UserNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}
}
这在我的服务中:
@GET
@Path("/user")
public Response getUser(@QueryParam("id") String id) throws UserNotFoundException{
//Some user validation code with DB hit, if not found then
throw new UserNotFoundException();
}
UserNotFoundException
是用户定义的
例外。
我试过这个:
public class UserNotFoundException extends Exception {
//SOME block of code
}
但是当我调用该服务时未调用 UserDefinedExceptionMapper
。似乎我可能会遗漏 UserDefinedException
中的内容。那么如何定义这个例外呢?
But when I invoke the service, the UserDefinedExceptionMapper
is not getting invoked. It seems I might be missing something in the UserDefinedException
. How to define this exception then?
请告诉我如何定义 UserNotFoundException
。
推荐答案
您需要使用 @Provider
,否则永远不会在JAX-RS运行时注册。
You need to annotate your exception mapper with @Provider
, otherwise it will never get registered with the JAX-RS runtime.
@Provider
public class UserNotFoundMapper implements
ExceptionMapper<UserNotFoundException> {
@Override
public Response toResponse(UserNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain")
.build();
}
}
这篇关于JAX-RS jersey ExceptionMappers用户定义的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!