Jersey 提供了几种方式,方便我们的开发。
一、WebApplicationException类
直接使用WebApplicationException或继承WebApplicationException构建具体的RuntimeException异常
public class InvalidParameterException extends WebApplicationException {
private static final long serialVersionUID = -8053837233933562857L;
public InvalidParameterException(int httpStatus, int errorCode, String errorMsg) {
super(Response.status(httpStatus).entity(new ExceptionEntity(httpStatus, errorCode, errorMsg))
.type(MediaType.APPLICATION_JSON).build());
}
}
比如创建一个不合法参数的异常类,并返回具体的错误信息。
但是这种处理方式,是很不友好的,可以通过方式2,构建异常框架,并返回Response对象。
二、ExceptionMapper接口
1、创建自定义异常的基类
public class ApplicationException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int code;
public ApplicationException(int code, String message) {
super(message);
this.code = code;
}
//。。。
}
2、创建参数异常类
public class InvalidParamException extends ApplicationException{
private static final long serialVersionUID = 1L;
public InvalidParamException(int code,String msg) {
super(code,msg);
}
}
3、创建自定义异常映射mapper
需要使用@Provider或者在ResourceConfig中注册
@Provider
public class ApplicationExceptionMapper implements ExceptionMapper<ApplicationException> {
@Override
public Response toResponse(ApplicationException exception) {
return Response.ok(new Result(exception.getCode(), exception.getMessage())).type(MediaType.APPLICATION_JSON)
.build();
}
}
public class Result {
private int code;
private Object data;
private String msg;
public Result() {
super();
}
public Result(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
4、直接调用
@GET
@Path("response")
public Response getResponse1() {
User user = new User();
user.setName("ddd");
user.setAge(123);
if(user.getAge()==123)
throw new InvalidParamException(3,"不能输入中文");
return Response.ok(user).build();
}
客户端调用,将会返回的是json格式数据,可以根据code进行对应的错误处理。