使用异常映射器的 JAX-RS

2024-04-11

我读到我可以创建一个实现javax.ws.rs.ext.ExceptionMapper它将把抛出的应用程序异常映射到Response目的。

我创建了一个简单的示例,如果在保留对象时电话长度大于 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);
            }
        }       
    }
}

Service:

@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();  
    }

}

InvalidDataException 是否被包裹在 PersistenceException 中?也许你可以做如下的事情:

@Provider 
public class PersistenceMapper implements ExceptionMapper<PersistenceException> { 

    @Override 
    public Response toResponse(PersistenceException arg0) { 
        if(arg0.getCause() instanceof InvalidDataException) {
           return Response.status(Response.Status.BAD_REQUEST).build(); 
        } else {
           ...
        }
    } 

} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用异常映射器的 JAX-RS 的相关文章

随机推荐