5

JBoss-7.1 と RESTEasy を使用して単純な RESTFul サービスを開発しています。次のように CustomerService という REST サービスがあります。

@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 制約が失敗し、画面にスタック トレースが表示されます。

これらの検証エラーをキャッチして、適切なエラー メッセージを含む xml 応答を準備し、ユーザーに表示する方法はありますか?

4

1 に答える 1

10

例外マッパーを使用する必要があります。例:

@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 にラップされたエラー メッセージが表示されます。

于 2012-05-09T21:28:33.857 に答える