이전에 블로깅했던 2009/06/05 - [나만의 작업] - Jersey의 Exception Handling 에 대해 조금 더 자세히 블로깅을 해봅니다. 

Jersey에서 Excpetion Handling하는 방법들

1) WebApplication을 상속한 새로운 클래스인 NotFoundException을 생성하여 던지기
 
NotFoundException을 throw하는 예
Example 1.25. Throwing Jersey specific exceptions to control response
  1 @Path("items/{itemid}/")
  2 public Item getItem(@PathParam("itemid") String itemid) {
  3     Item i = getItems().get(itemid);
  4     if (i == null)
  5         throw new NotFoundException("Item, " + itemid + ", is not found");
  6
  7     return i;
  8 }


이방법은 WebApplicationException을 상속받은 NotFoundException을 이용하는 방법

Example 1.26. Jersey specific exception implementation
  1 public class NotFoundException extends WebApplicationException {
  2
  3     /**
  4      * Create a HTTP 404 (Not Found) exception.
  5      */
  6     public NotFoundException() {
  7         super(Responses.notFound().build());
  8     }
  9
 10     /**
 11      * Create a HTTP 404 (Not Found) exception.
 12      * @param message the String that is the entity of the 404 response.
 13      */
 14     public NotFoundException(String message) {
 15         super(Response.status(Responses.NOT_FOUND).
 16                 entity(message).type("text/plain").build());
 17     }
 18
 19 }


이렇게 status를 나타내고 response를 전송할때 타입까지 정해서 보내줄 수 있다.


2) 직접 WebApplicationException에 Response status로 바로 던지기.
@Path("accounts/{accountId}/")
public Item getItem(@PathParam("accountId") String accountId) {
   
// An unauthorized user tries to enter
   
throw new WebApplicationException(Response.status.UNAUTHORIZED);
}


3) ExceptionMapper 이용하는 예

Example 1.27. Mapping generic exceptions to responses
  1 @Provider
  2 public class EntityNotFoundMapper implements
  3         ExceptionMapper<javax.persistence.EntityNotFoundException> {
  4     public Response toResponse(javax.persistence.EntityNotFoundException ex) {
  5         return Response.status(404).
  6             entity(ex.getMessage()).
  7             type("text/plain").
  8             build();
  9     }
 10 }


클래스가 @Provider로 정의되어 있고 javax.persistence.EntityNotFoundException의 toResponse메소드를 이용해 Excpetion을 Response의 status로 매핑해서 이용할 수 있다.



참고
-------------------------------------------------------------------------------------------------------------------------------------
1) Jersey 1.0.3 UserGuide 내용 중의 " WebApplicationException and Mapping Exception to Responses"
2) 
JAX-RS / Jersey how to customize error handling?
3)
  Putting Java to REST





이올린에 북마크하기(0) 이올린에 추천하기(0)

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

Jersey의 Exception Handling

Posted at 2009/06/05 14:02// Posted in 나만의 작업

Jersey에서는 WebApplicationException 클래스를 이용하여 Exception Handling한다.

WebApplicationException을 잡아야 하고, 예외를 Response로 매핑한다.
예외를 위한 response가 null이 아니면 응답을 생성, null이면 서버 오류 응답을 생성
런타임 예외나 미리감지되는 예외(checked exception) 기호에 따라 사용
미리 감지되지 않는 예외나 오류는 컨테이너 안쪽까지 전파가 되도록 예외를 다시 던져야(re-thrown) 한다.
미리 감지되는 예외나 throwable 은 직접 예외를 던지지 말고, 서블릿인 경우은  ServletException으로, JAX-WS Provider 기반인 경우는 WebServiceException으로 예외를 감싸서 던져야 한다.


 public SparklinesResource(
          @QueryParam("d") IntegerList data,
          @DefaultValue("0,100") @QueryParam("limits") Interval limits) {
      if (data == null)
          throw new WebApplicationException(400);
  
      this.data = data;  
      this.limits = limits;
  
      if (!limits.contains(data))
          throw new WebApplicationException(400);


* 참고 : 이 예제는 Joe Gregorio의  Sparklines service and python implementation을 보고 영감을 받고 Paul Sandoz 아저씨가 만든 Sparklines 예제중의 일부이다.



이올린에 북마크하기(0) 이올린에 추천하기(0)

'나만의 작업' 카테고리의 다른 글

[Jersey] WebApplicationException and Mapping Exception to Responses  (0) 2009/07/30
[Jersey] Building Responses  (4) 2009/07/21
[Jersey] Representation and Java Types  (0) 2009/07/16
Jersey의 JSON Support  (2) 2009/06/08
Jersey의 Exception Handling  (0) 2009/06/05
Jersey의 Return Type  (0) 2009/06/04
Jersey의 MessageBodyReader/Writer  (0) 2009/06/03
JAX-RS @Produces와 @Consumes  (2) 2009/06/02
JAX-RS의 구성  (0) 2009/06/01

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret