수입 잭슨 클래스를 피하기 만에 충실 순수한 JAX-RS 클래스 이런 json 예외 래퍼를 만든다.
ExceptionInfo 랩퍼를 작성하고 다양한 예외 상태 유형을 서브 클래스하십시오.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class ExceptionInfo {
private int status;
private String msg, desc;
public ExceptionInfo(int status, String msg, String desc) {
this.status=status;
this.msg=msg;
this.desc=desc;
}
@XmlElement public int getStatus() { return status; }
@XmlElement public String getMessage() { return msg; }
@XmlElement public String getDescription() { return desc; }
}
- - - -
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.WebApplicationException;
/**
* Create 404 NOT FOUND exception
*/
public class NotFoundException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public NotFoundException() {
this("Resource not found", null);
}
/**
* Create a HTTP 404 (Not Found) exception.
* @param message the String that is the entity of the 404 response.
*/
public NotFoundException(String msg, String desc) {
super(Response.status(Status.NOT_FOUND).entity(
new ExceptionInfo(Status.NOT_FOUND.getStatusCode(), msg, desc)
).type("application/json").build());
}
}
은 다음 리소스 구현에 예외를 발생하고 클라이언트는 좋은 JSON 형식의 HTTP 오류 몸을받습니다.
@Path("/properties")
public class PropertyService {
...
@GET @Path("/{key}")
@Produces({"application/json;charset=UTF-8"})
public Property getProperty(@PathParam("key") String key) {
// 200=OK(json obj), 404=NotFound
Property bean = DBUtil.getProperty(key);
if (bean==null) throw new NotFoundException();
return bean;
}
...
}
- - - -
Content-Type: application/json
{"status":404,"message":"Resource not found","description":null}
감사합니다. jgm. 죄송합니다. Jacson의'ObjectMapper'를'ExceptionMapper'에있는'ErrorInfo' 객체로부터 JSON 문자열을 생성하기 위해 어떻게 인코딩합니까? 미리 감사드립니다 –
전체 예제를 추가했습니다. – jgm
마지막 질문 만 jgm. 저는 Jetty - Jersey 환경에 있으며, 예외에서 항상 null을 얻습니다 .getMessage(). 상태 설명 만 반환하고 싶습니다. 미리 감사드립니다. –