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

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

问题描述

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

  @Path(/ hello)
public class HelloWorldResource {

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

//返回一个名称和年龄的问候语
}
}

这样做很好,可以处理Date(String)构造函数所理解的当前语言环境中的任何格式(如YYYY / mm / dd和mm / dd / YYYY)。但是如果我提供一个无效或不明白的值,我会收到一个404的回复。



例如:



< pre class =lang-none prettyprint-override> GET / hello?name = Mark& birthDate = X

404未找到

如何自定义此行为?也许是一个不同的响应代码(可能是400错误请求)?记录错误怎么办?也许在自定义标题中添加问题描述(日期格式错误)以帮助进行故障排除?或返回一个完整的错误响应与细节,连同一个5xx状态代码?

解决方案

有几种方法来自定义错误处理JAX-RS行为。这里有三个简单的方法。



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



示例:

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

并且抛出这个新创建的异常你简单地: / p>

  @Path(accounts / {accountId} /)
public Item getItem(@PathParam(accountId String accountId){
//未经授权的用户尝试输入
抛出新的NotAuthorizedException(您没有权限);
}

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



第二个更简单的方法是直接在代码中构造WebApplicationException的一个实例。只要您不必实现自己的应用程序异常,此方法就可以工作。



示例:

  @Path(accounts / {accountId} /)
public Item getItem(@PathParam(accountId)String accountId){
//未经授权的用户尝试输入
抛出新的WebApplicationException(Response.Status.UNAUTHORIZED);
}

此代码也返回401给客户端。



当然这只是一个简单的例子。如果需要,您可以使异常复杂得多,您可以生成所需的http响应代码。



另一种方法是将一个现有的Exception(或许是一个ObjectNotFoundException)包含在一个小的包装器类中,该类实现了使用@Provider注释注释的ExceptionMapper接口。这告诉JAX-RS运行时,如果引发的Exception异常,返回ExceptionMapper中定义的响应代码。


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
    }
}

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.

For example:

GET /hello?name=Mark&birthDate=X

404 Not Found

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?

解决方案

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

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

Example:

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");
}

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.

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.

Example:

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

This code too returns a 401 to the client.

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.

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天全站免登陆