Java 使用异常映射器的 JAX-RS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3293599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:47:41  来源:igfitidea点击:

JAX-RS using exception mappers

javaexception-handlingjakarta-eejerseyjax-rs

提问by Jordan Allan

I have read that I can create an implementation of javax.ws.rs.ext.ExceptionMapperthat will map a thrown application exception to a Responseobject.

我已经读到我可以创建一个实现javax.ws.rs.ext.ExceptionMapper,将抛出的应用程序异常映射到一个Response对象。

I've created a simple example which throws an exception if the phone length is greater than 20 characters when persisting the object. I am expecting the exception to be mapped to an HTTP 400 (Bad Request) response; however, I am receiving an HTTP 500 (Internal Server Error) with the following exception:

我创建了一个简单的示例,如果在持久化对象时电话长度大于 20 个字符,则会引发异常。我期望将异常映射到 HTTP 400(错误请求)响应;但是,我收到 HTTP 500(内部服务器错误),但有以下异常:

java.lang.ClassCastException: com.example.exception.InvalidDataException cannot be cast to java.lang.Error

What am I missing? Any advice is greatly appreciated.

我错过了什么?任何意见是极大的赞赏。

Exception mapper:

异常映射器:

@Provider
public class InvalidDataMapper implements ExceptionMapper<InvalidDataException> {

    @Override
    public Response toResponse(InvalidDataException arg0) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}

Exception class:

异常类:

public class InvalidDataException extends Exception {

    private static final long serialVersionUID = 1L;

    public InvalidDataException(String message) {
        super(message);
    }

    ...

}

Entity class:

实体类:

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

}

采纳答案by bdoughan

Is InvalidDataException getting wrapped in a PersistenceException? Maybe you could do something like the following:

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

} 

回答by Ashish

Cross check you web.xml you need to register your "PersistenceMapper" class also along with the services.

交叉检查您的 web.xml,您还需要将“PersistenceMapper”类与服务一起注册。