JAX-RS/Jersey 如何自定义错误处理? [英] JAX-RS / Jersey how to customize error handling?

查看:34
本文介绍了JAX-RS/Jersey 如何自定义错误处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jersey 学习 JAX-RS(又名 JSR-311).我已经成功创建了一个根资源并且正在使用参数:

I'm learning JAX-RS (aka, JSR-311) using Jersey. I've successfuly created a Root Resource and am playing around with parameters:

@Path("/hello")
public class HelloWorldResource {

    @GET
    @Produces("text/html")
    public String get(
        @QueryParam("name") String name,
        @QueryParam("birthDate") Date birthDate) {

         // Return a greeting with the name and age
    }
}

这很好用,并且可以处理 Date(String) 构造函数理解的当前语言环境中的任何格式(如 YYYY/mm/dd 和 mm/dd/YYYY).但如果我提供的值无效或不被理解,我会收到 404 响应.

This works great, and handles any format in the current locale which is understood by the Date(String) constructor (like YYYY/mm/dd and mm/dd/YYYY). But if I supply a value which is invalid or not understood, I get a 404 response.

例如:

GET /hello?name=Mark&birthDate=X

404 Not Found

如何自定义此行为?也许不同的响应代码(可能是400 Bad Request")?记录错误怎么样?也许在自定义标题中添加问题描述(错误的日期格式")以帮助进行故障排除?或者返回包含详细信息的完整错误响应以及 5xx 状态代码?

How can I customize this behavior? Maybe a different response code (probably "400 Bad Request")? What about logging an error? Maybe add a description of the problem ("bad date format") in a custom header to aid troubleshooting? Or return a whole Error response with details, along with a 5xx status code?

推荐答案

有多种方法可以使用 JAX-RS 自定义错误处理行为.以下是三种更简单的方法.

There are several approaches to customize the error handling behavior with JAX-RS. Here are three of the easier ways.

第一种方法是创建一个扩展 WebApplicationException 的 Exception 类.

The first approach is to create an Exception class that extends WebApplicationException.

示例:

public class NotAuthorizedException extends WebApplicationException {
     public NotAuthorizedException(String message) {
         super(Response.status(Response.Status.UNAUTHORIZED)
             .entity(message).type(MediaType.TEXT_PLAIN).build());
     }
}

并抛出这个新创建的异常,你只需:

And to throw this newly create Exception you simply:

@Path("accounts/{accountId}/")
    public Item getItem(@PathParam("accountId") String accountId) {
       // An unauthorized user tries to enter
       throw new NotAuthorizedException("You Don't Have Permission");
}

注意,您不需要在 throws 子句中声明异常,因为 WebApplicationException 是运行时异常.这将向客户端返回 401 响应.

Notice, you don't need to declare the exception in a throws clause because WebApplicationException is a runtime Exception. This will return a 401 response to the client.

第二种更简单的方法是直接在您的代码中构建 WebApplicationException 的实例.只要您不必实现自己的应用程序异常,这种方法就有效.

The second and easier approach is to simply construct an instance of the WebApplicationException directly in your code. This approach works as long as you don't have to implement your own application Exceptions.

示例:

@Path("accounts/{accountId}/")
public Item getItem(@PathParam("accountId") String accountId) {
   // An unauthorized user tries to enter
   throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}

此代码也会向客户端返回 401.

This code too returns a 401 to the client.

当然,这只是一个简单的例子.如有必要,您可以使异常更加复杂,并且您可以生成您需要的任何 http 响应代码.

Of course, this is just a simple example. You can make the Exception much more complex if necessary, and you can generate what ever http response code you need to.

另一种方法是包装一个现有的异常,可能是一个 ObjectNotFoundException 和一个小的包装类,它实现了 ExceptionMapper 接口,用 @Provider注释.这告诉 JAX-RS 运行时,如果引发了包装的异常,则返回 ExceptionMapper 中定义的响应代码.

One other approach is to wrap an existing Exception, perhaps an ObjectNotFoundException with an small wrapper class that implements the ExceptionMapper interface annotated with a @Provider annotation. This tells the JAX-RS runtime, that if the wrapped Exception is raised, return the response code defined in the ExceptionMapper.

这篇关于JAX-RS/Jersey 如何自定义错误处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆