我读过,我可以创建一个javax.ws.rs.ext.ExceptionMapper
的实现,它将引发的应用程序异常映射到Response
对象。使用异常映射器的JAX-RS
我创建了一个简单的例子,如果手机长度大于20个字符时持续对象引发异常。我希望将异常映射到HTTP 400(错误请求)响应;不过,我收到一个HTTP 500(内部服务器错误),但下列情况除外:
java.lang.ClassCastException: com.example.exception.InvalidDataException cannot be cast to java.lang.Error
我缺少什么?任何意见是极大的赞赏。
异常映射器:
@Provider
public class InvalidDataMapper implements ExceptionMapper<InvalidDataException> {
@Override
public Response toResponse(InvalidDataException arg0) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
异常类:
public class InvalidDataException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidDataException(String message) {
super(message);
}
...
}
实体类:
@Entity
@Table(name="PERSON")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
private Long id;
@Column(name="NAME")
private String name;
@Column(name="PHONE")
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@PrePersist
public void validate() throws InvalidDataException {
if (phone != null) {
if (phone.length() > 20) {
throw new InvalidDataException("Phone number too long: " + phone);
}
}
}
}
服务:
@Path("persons/")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
@Stateless
public class PersonResource {
@Context
private UriInfo uriInfo;
@PersistenceContext(name="simple")
private EntityManager em;
@POST
public Response createPerson(JAXBElement<Person> personJaxb) {
Person person = personJaxb.getValue();
em.persist(person);
em.flush();
URI personUri = uriInfo.getAbsolutePathBuilder().
path(person.getId().toString()).build();
return Response.created(personUri).build();
}
}
谢谢布莱斯,那工作。为什么我必须在PersistenceException中包装InvalidDataException?根据我的书籍之一,它表示如果注册异常映射器,JAX-RS运行时将处理任何抛出的异常。就我而言,我为InvalidDataException注册了一个异常映射器... – 2010-07-28 19:30:50
JPA实现将捕获InvalidDataException并将其包装在PersistenceException中。然后你的JAX-RS实现将会得到一个PersistenceException。这就是为什么你需要打开它。 – 2010-07-28 19:45:13
另请参阅http://stackoverflow.com/questions/3249495/call-exceptionmapper-from-another-exceptionmapper-in-jax-rs – 2010-07-28 19:52:04