How to catch RESTEasy Bean Validation Errors?

后端 未结 1 655
执笔经年
执笔经年 2020-12-18 10:21

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\")
         


        
相关标签:
1条回答
  • 2020-12-18 11:16

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

    where Error could be something like:

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

    Then you'll get error message wrapped into XML.

    0 讨论(0)
提交回复
热议问题