如何捕获RESTEasy Bean验证错误? [英] How to catch RESTEasy Bean Validation Errors?

查看:87
本文介绍了如何捕获RESTEasy Bean验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JBoss-7.1和RESTEasy开发一个简单的RESTFul服务. 我有一个称为CustomerService的REST服务,如下所示:

I am developing a simple RESTFul service using JBoss-7.1 and RESTEasy. I have a REST Service, called CustomerService as follows:

@Path(value="/customers")
@ValidateRequest
class CustomerService
{
  @Path(value="/{id}")
  @GET
  @Produces(MediaType.APPLICATION_XML)
  public Customer getCustomer(@PathParam("id") @Min(value=1) Integer id) 
  {
    Customer customer = null;
    try {
        customer = dao.getCustomer(id);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return customer;
    }
}

在这里,当我点击url http://localhost:8080/SomeApp/customers/-1 ,那么@Min约束将失败并在屏幕上显示堆栈跟踪.

Here when I hit the url http://localhost:8080/SomeApp/customers/-1 then @Min constraint will fail and showing the stacktrace on the screen.

是否可以捕获这些验证错误,以便我可以准备带有正确错误消息的xml响应并显示给用户?

Is there a way to catch these validation errors so that I can prepare an xml response with proper error message and show to user?

推荐答案

您应使用异常映射器.示例:

You should use exception mapper. Example:

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<javax.validation.ConstraintViolationException> {

    public Response toResponse(javax.validation.ConstraintViolationException cex) {
       Error error = new Error();
       error.setMessage("Whatever message you want to send to user. " + cex);
       return Response.entity(error).status(400).build(); //400 - bad request seems to be good choice
    }
}

其中错误可能类似于:

@XmlRootElement
public class Error{
   private String message;
   //getter and setter for message field
}

然后,您将获得包装为XML的错误消息.

Then you'll get error message wrapped into XML.

这篇关于如何捕获RESTEasy Bean验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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