Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Rest Handling Exception

JAX-RS is a collection of interfaces and Java annotations that simplifies development of server-side REST applications. Representational State Transfer (REST) applications are easier to develop and easier to consume when compared to other types of distributed systems. JAX-RS applications can produce exceptions and errors. This post covers how to customize or handle server side checked and unchecked exceptions using Jersey ExceptionMapper.
In this post I will present how I've designed and implemented the error handling of a REST API with the help Jersey framework. To handle custom exception in JAX-RS based web services, you should create an exception class and then implement the ExceptionMapper interface.
Introduction to WebApplicationException JAX-RS introduced the exception, javax.ws.rs.WebApplicationException. You can specify a specific error class name or javax.ws.rs.core.Response object when creating javax.ws.rs.WebApplicationException. When the javax.ws.rs.WebApplicationException is thrown, the information included in the exception by way of a status class name or Response object is used to serialize a response. This exception may be thrown by a resource method, provider or javax.ws.rs.core.StreamingOutput implementation if a specific HTTP error response needs to be produced. Let's show the structure of the project:



pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.rest.technology</groupId>
<artifactId>RestWebService</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>RestWebService</name>

<build>
<finalName>RestWebService</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version></version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId
if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
</dependencies>
<properties>
<jersey.version>2.21</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>


In this pom.xml, I have used jersey-media-moxy dependency for getting JSON response and jersey-container-servlet-core dependency is used to configure Jersey dependency with this project.



you create a file called web.xml in the WebContent\WEB-INF folder as the following:

web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>

<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Jersey Web Application </servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>
jersey.config.server.provider.packages </param-name>
<param-value>com.rest.technology </param-value>
</init-param>
<load-on-startup>1 </load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Web Application </servlet-name>
<url-pattern>/webapi/* </url-pattern>
</servlet-mapping>

</web-app>

In web.xml, I am using org.glassfish.jersey.servlet.ServletContainer servlet for configure restful webservice. I have configure com.rest.technology package for searching all annotations and create a one instance when application start using load-on-startup. In this example /webapi/* pattern use for restful URL.



index.jsp
<html>
<body>
<h2>Jersey RESTful Web Application!</h2>
for more information on Jersey!
</body>
</html>

index.jsp is used for welcome file when this application run.

EmployeeNotFoundException.java
package com.rest.technology.exception;

public class EmployeeNotFoundException extends Exception {

private static final long serialVersionUID = 1L;

public EmployeeNotFoundException() {
super("Employee is not found");
}

public EmployeeNotFoundException(String customMessage) {
super(customMessage);
}
public EmployeeNotFoundException(String customMessage, Throwable cause) {
super(customMessage, cause);
}

}

EmployeeNotFoundException is a custom class exception which extends exception class. It have two constructor for setting exception message.



EmployeeThrowingCustomWebAppException.java
package com.rest.technology.exception;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.rest.technology.model.Employee;

@Path("employeethrowingcustomwebappexception")
public class EmployeeThrowingCustomWebAppException {

@GET
@Path("{id}")
@Produces("application/xml")
public Employee getEmployee(@PathParam("id") int employeeId) {
if (employeeId != 1) {
throw new EmployeeNotFoundException("Employee, " + employeeId
+ ", is not found");
}

Employee myEmployee = new Employee();
myEmployee.setId(employeeId);
myEmployee.setName("Vaibhav Sharma");
myEmployee.setAddress("New Delhi");
myEmployee.setSalary(100000);

return myEmployee;
}

public class EmployeeNotFoundException extends
WebApplicationException {

private static final long serialVersionUID = 1L;

public EmployeeNotFoundException() {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.build());
}

public EmployeeNotFoundException(String message) {
super(Response.status(Response.Status.NOT_FOUND)
.entity(message).type(MediaType.TEXT_PLAIN).build());
}

}

}

EmployeeThrowingCustomWebAppException is a rest application mapping which is used to received request when request path match with employeethrowingcustomwebappexception and id variable value like employeethrowingcustomwebappexception/1. This class will throw EmployeeNotFoundException custom exception when employeeId is not equal to 1.



EmployeeThrowingWebAppException.java
package com.rest.technology.exception;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.rest.technology.model.Employee;

@Path("employeethrowingwebappexception")
@Produces("application/xml")
public class EmployeeThrowingWebAppException {

@GET
@Path("{id}")
@Produces("application/xml")
public Employee getEmployee(@PathParam("id") int employeeId) {
if (employeeId != 1) {
throw new WebApplicationException(Response.status(
Response.Status.INTERNAL_SERVER_ERROR).type(
MediaType.TEXT_PLAIN).entity(
"Employee, " + employeeId + ", is not found").build());
}

Employee myEmployee = new Employee();
myEmployee.setId(employeeId);
myEmployee.setName("Vaibhav Sharma");
myEmployee.setAddress("Mumbai");
myEmployee.setSalary(200000);

return myEmployee;
}

}



EmployeeNotFoundExceptionMapper.java
package com.rest.technology.mapper;

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 com.rest.technology.exception.EmployeeNotFoundException;

@Provider
public class EmployeeNotFoundExceptionMapper implements
ExceptionMapper<EmployeeNotFoundException> {

@Override
public Response toResponse(
EmployeeNotFoundException employeeNotFoundCustomException) {

return Response.status(Response.Status.NOT_FOUND).entity(
employeeNotFoundCustomException.getMessage()).type(
MediaType.TEXT_PLAIN).build();

}
}



EmployeeNotFoundExceptionMapper.java
package com.rest.technology.mapper;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.rest.technology.exception.EmployeeNotFoundException;
import com.rest.technology.model.Employee;

@Path("employeethrowingmapperexception")
@Produces("application/xml")
public class EmployeeThrowingExceptionMapper {

@GET
@Path("{id}")
@Produces("application/xml")
public Employee getEmployee(@PathParam("id") int employeeId)
throws EmployeeNotFoundException {
if (employeeId != 1) {
throw new EmployeeNotFoundException("Employee, " + employeeId
+ ", is not found");
}

Employee myEmployee = new Employee();
myEmployee.setId(employeeId);
myEmployee.setName("Vaibhav Sharma");
myEmployee.setAddress("New York");
myEmployee.setSalary(300000);

return myEmployee;
}

}



Employee.java
package com.rest.technology.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {

int id = 0;
String name = "";
String address = "";
int salary = 0;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

you can test above code using below URLs. See previous tutorial for how to run this code in rest api either using postman or rest client
http://localhost:8080/Rest_Exception/restapi/employeethrowingcustomwebappexception/1
http://localhost:8080/Rest_Exception/restapi/employeethrowingcustomwebappexception/10
http://localhost:8080/Rest_Exception/restapi/employeethrowingmapperexception/1
http://localhost:8080/Rest_Exception/restapi/employeethrowingmapperexception/10


     << Previous
Next >>