JAX-RS支持处理自定义异常(以EJB或CID Bean形式抛出)以处理自定义HTTP响应。
假设我们有一个“异常” EJB:
@Stateless
public class Hello {
public String greeting() {
if (new Random().nextBoolean())
throw new GreetingException("Could not greet");
return "hello";
}
}
@ApplicationException
public class GreetingException extends RuntimeException {
public GreetingException(String message) {
super(message);
}
}
EJB在我们的JAX-RS资源中使用:
@Path("hello")
public class HelloResource {
@Inject
Hello hello;
@GET
public String hello() {
return hello.greeting();
}
}
现在,将发生的异常映射到自定义HTTP响应,我们可以定义JAX-RS ExceptionMapper
。
@Provider
public class GreetingExceptionMapper implements ExceptionMapper<GreetingException> {
@Override
public Response toResponse(GreetingException exception) {
return Response.status(Response.Status.CONFLICT)
.header("Conflict-Reason", exception.getMessage())
.build();
}
}
异常映射器注册为JAX-RS扩展(由@Provider
),并将处理资源方法引发的任何GreetingException
。
该示例偶尔会输出带有标头Conflict-Reason: Could not greet
HTTP 409 Conflict
。
如果使用CDI托管bean而不是EJB,则不需要@ApplicationException
批注。
翻译自: https://www.javacodegeeks.com/2017/12/handle-custom-exception-types-jax-rs.html