WebApplicationException
@Path("exception") public class ExceptionResource { @POST @Path("register") public Response register(@FormParam("name")String username) { if ("admin".equals(username)) { throw new WebApplicationException("用户名已经存在!", Response.Status.CONFLICT); } else { return Response.ok("注册成功!", MediaType.TEXT_PLAIN).build(); } } }
ExceptionMapper
public interface ExceptionMapper<E extends Throwable> { Response toResponse(E exception); }
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> { @Override public Response toResponse(JsonMappingException exception) { return Response.status(Response.Status.BAD_REQUEST) .entity(exception.getMessage()) .type("text/plain").build(); } }
@Getter public enum ExceptionCode { DEFAULT_ERROR(0), PERMISSION_EXCEPTION(1), MONEY_CHECK_EXCEPTION(2), ACCOUNT_STATUS_ERROR(3); private ExceptionCode(int code) { this.code = code; } private int code; }
@Getter public abstract class ApplicationException extends RuntimeException { private static final long serialVersionUID = 1L; private ExceptionCode code = ExceptionCode.DEFAULT_ERROR; public ApplicationException(String msg) { super(msg); } public ApplicationException(String msg, ExceptionCode code) { super(msg); this.code = code; } public ApplicationException(String msg, ExceptionCode code, Throwable cause) { super(msg, cause); this.code = code; } }
public class PermissionException extends ApplicationException { private static final long serialVersionUID = 1L; public PermissionException(String msg, Throwable ex) { super(msg, ExceptionCode.PERMISSION_EXCEPTION, ex); } }
@Provider public class ApplicationExceptionMapper implements ExceptionMapper<ApplicationException> { @Override public Response toResponse(ApplicationException exception) { AjaxResult result = new AjaxResult(false, exception.getMessage(), null, exception.getCode().getCode()); return Response.ok(result, MediaType.APPLICATION_JSON).build(); } }
@Setter @Getter @NoArgsConstructor @AllArgsConstructor public class AjaxResult { private boolean success;//请求是否执行成功 private String msg;//本次请求的消息 private Object data;//本次请求可能携带的内容对象 private int code;//如果出现异常,code代表异常类型码 }
@GET @Path("resource") @Produces(MediaType.APPLICATION_JSON) public AjaxResult doSomething(@HeaderParam("token") String token) { if ("token".equals(token)) { return new AjaxResult(true, "正常访问资源", "some logic value", 0); } else { throw new PermissionException("没有权限访问该资源", null); } }
下一节,我们将介绍Jersey和Spring以及SpringBoot的集成开发。