users@jersey.java.net

Re: [Jersey] http status codes in custom exceptions

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 15 Apr 2010 15:10:07 +0200

On Apr 15, 2010, at 8:06 AM, Suchitha Koneru (sukoneru) wrote:

> Hello Jersey users ,
> I am using Jersey 1.1.1-ea with JDK 1.6. We are
> using custom exception class along with exception mapper as shown
> below
>
>
> public class SmartServicesRSException extends
> WebApplicationException {
>
> public Response.Status httpStatus;
>
> public String applicationErrCode;
>
>
> public SmartServicesRSException(int httpStatusCode , String
> applicationErrCode){
> super(httpStatusCode);
> this.applicationErrCode = applicationErrCode;
> this.httpStatus =
> Response.Status.fromStatusCode(httpStatusCode);
> }
>
> }
>
>
>
> @Provider
> public class SmartServicesExceptionMapper implements
> ExceptionMapper<SmartServicesRSException>{
>
> public Response toResponse(SmartServicesRSException exception) {
> // TODO Auto-generated method stub
> System.out.println("the application error code
> is :"+exception.applicationErrCode);
>
> returnResponse
> .status
> (exception
> .httpStatus
> ).entity(newGenericEntity<String>(exception.applicationErrCode)
> {}).type("application/text").build();
>
> }
> }
>

The use of GenericEntity is redundant here. You can just do:

   return Response.status(exception.httpStatus).
     entity(exception.applicationErrCode).
     type("application/text").build();

Use GenericEntity when the generic type information of the entity
needs to be preserved at runtime, for example if you use a list of
JAXB beans such as List<MyJaxbBean>.

Paul.

>
> The TCP trace captured in the run time shows a status code of 0 ,
> even when I am passing a valid HTTP status code as shown below
>
>
> @GET
> @Path("400")
> @Produces("application/text")
> public String testBadRequest() throws SmartServicesRSException {
> throw new
> SmartServicesRSException
> (Response.Status.BAD_REQUEST,"input.error.code");
> }
>
>
> TCP Response trace
>
> HTTP/1.1 400 Bad Request
> Server: Apache-Coyote/1.1
> X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1
> Content-Type: application/text
> Transfer-Encoding: chunked
> Date: Thu, 15 Apr 2010 05:58:52 GMT
> Connection: close
>
> 10
> input.error.code
> 0
>
> Could you please let me know , if there is anything missing in my
> approach. The status code is sent as 0 as per the last line of the
> output.
>
> Thanks,
> Suchitha