Tuesday, October 27, 2015

Exception handling using ExceptionMapper in RESTFul webservices using JAX-RS

ExceptionHandlingExample.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 ExceptionHandlingExample {

 @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 per.sample.rest.bean.ErrorResponse;

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();

    }

}


ErrorResponse.java

###############################################

package per.sample.rest.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "errorResponse")
public class ErrorResponse {

 private String errorCode;
 private int errorId;

 public String getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(String errorCode) {
  this.errorCode = errorCode;
 }

 public int getErrorId() {
  return errorId;
 }

 public void setErrorId(int errorId) {
  this.errorId = errorId;
 }

}


No comments:

Post a Comment