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.
我使用 ExceptionMappers
创建了一个 UserNotFoundMapper
,如下所示:
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
是一个 User-Defined
异常.
我试过了:
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屋!