原文: https://howtodoinjava.com/resteasy/resteasy-exceptionmapper-example/
学习使用 resteasy ExceptionMapper接口实现创建和处理自定义异常。 ExceptionMapper是供应器的契约,该供应器将 Java 异常映射到Response对象。
必须使用
@Provider注解ExceptionMapper接口的实现才能正常工作。
1. Resteasy ExceptionMapper - 自定义异常处理器
ExceptionMapper的示例实现供应器类如下所示:
package com.howtodoinjava.exception;import javax.ws.rs.core.Response;import javax.ws.rs.core.Response.Status;import javax.ws.rs.ext.ExceptionMapper;import javax.ws.rs.ext.Provider;@Providerpublic class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException>{@Overridepublic Response toResponse(MyApplicationException exception){return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();}}
自定义异常类MyApplicationException.java的编写方式为:
package com.howtodoinjava.exception;import java.io.Serializable;public class MyApplicationException extends Exception implements Serializable{private static final long serialVersionUID = 1L;public MyApplicationException() {super();}public MyApplicationException(String msg) {super(msg);}public MyApplicationException(String msg, Exception e) {super(msg, e);}}
2. Resteasy REST API
为了测试ExceptionMapper实现,我编写了以下 resteasy REST API。
package com.howtodoinjava.rest;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.core.Response;import org.jboss.resteasy.spi.validation.ValidateRequest;import com.howtodoinjava.exception.MyApplicationException;@Path("/rest")public class UserService{@Path("/users/{id}")@GET@ValidateRequestpublic Response getUserBId ( @PathParam("id") String id ) throws MyApplicationException{//validate mandatory fieldif(id == null){throw new MyApplicationException("id is not present in request !!");}//Validate proper formattry{Integer.parseInt(id);}catch(NumberFormatException e){throw new MyApplicationException("id is not a number !!");}//Process the requestreturn Response.ok().entity("User with ID " + id + " found !!").build();}}
3. RESTEasy ExceptionMapper 演示
上面的 API 接受Integer格式的用户'id'参数。 如果我们以无法解析为Integer的其他格式传递 id,则会抛出MyApplicationException。 我们的异常映射器应该能够处理这个问题。
3.1 有效请求
在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1。

REST API 的有效请求
3.2 无效的请求 - 引发异常
在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc。

REST API 的无效请求
要下载这个使用ExceptionMapper接口的 Resteasy 客户端异常处理示例的源代码,请遵循以下给定的链接。
学习愉快!
