Tuesday, January 5, 2016

RESTful Web services - Exception Handling

SampleExceptionHandlingResoruce.java


package per.sample.rest.service;

import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import per.sample.rest.exception.CustomException;

@Path("/exception")
public class SampleExceptionHandlingResoruce {

@GET
@Path("{name}")
@Produces(MediaType.TEXT_PLAIN)
public String sayHello(@PathParam("name") String name) {
System.out.println(" %%%%%%%%%%%%%%%%%%%%%%% : "+name);
if(name == null || name.isEmpty())
throw new CustomException("Invalid name");
else
return "Hello !"+name;
}
}


CustomException.java

package per.sample.rest.exception;

public class CustomException  extends RuntimeException{

/**
*/
private static final long serialVersionUID = 1L;

public CustomException() {
super();
}

public CustomException(String message, Throwable e) {
super(message, e);
}

public CustomException(String arg0) {
super(arg0);
}

public CustomException(Throwable arg0) {
super(arg0);
}

public int getErrorId() {
// TODO Auto-generated method stub
return 0;
}

}


CustomExceptionMapper.java

package per.sample.rest.exception;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import per.sample.rest.bean.ErrorResponse;

/**
 * javax.ws.rs.ext.ExceptionMapper is Contract for a provider 
 * that maps Java exceptions to Response. 
 * An implementation of this interface must be annotated with Provider. 
 *
 */
@Provider
public class CustomExceptionMapper implements ExceptionMapper<CustomException> {

public Response toResponse(
CustomException exception) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setErrorId(exception.getErrorId());
        errorResponse.setErrorCode(exception.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
                errorResponse).type(
                MediaType.APPLICATION_XML).build();
 
    }

}



No comments:

Post a Comment