The best part of Spring framework is that it address all issues about which an application developer will be concerned. One such concern for developers is error handling or exception handling in web based applications and web services. There is very innovative way in which error/exception handlers can be configured in a Spring controller. The error handler is automatically invoked in case of any exception without each individual method requiring to introduce boilerplate try-catch or repetitive code.

We shall this being implemented for Spring based web services, but this practices listed here should be followed by web services implemented using any framework/platform. The underlying thought is to make the web service client aware of proper error message and HTTP response code.

Demo URL’s

Let us first start with the demo. Click on each of the following demo buttons to see what you will achieve:

Success response from web service

Error response from web service

Sample Spring controller code

In this tutorial we shall see how to configure exception handler for a RESTful web service application. You need to perform following tasks for proper error handling:

a) Validate user input.
b) Do exception handling using ExceptionHandler method in controller code.

The code is same from my REST web service beginners tutorial with added error handler method:

package com.javaexperience.main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.javaexperience.employee.Employee;

@Controller
public class EmpController 
{
	List<Employee> list = new ArrayList<Employee>();  
	
	//Steps followed in this code are:
	//1) Validate the input
	//2) Do processing
	//3) Return appropriate HTTP code and message.

	@RequestMapping(value = "/getEmp/{emp}", method = RequestMethod.GET)
	public ResponseEntity<?> getEmployee(@PathVariable("emp") int empid) {
		if(empid < 0) {
			return new ResponseEntity<String>("Employee Id is not valid.", HttpStatus.BAD_REQUEST);
		}
		
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee emp = (Employee) iterator.next();
			if(emp.getEmpId()==empid) {
				return new ResponseEntity<Employee>(emp,HttpStatus.OK);
			}
		}
		return new ResponseEntity<String>("Employee with id: " + empid + " not found.", HttpStatus.NOT_FOUND);
	}

	@RequestMapping(value = "/removeEmp/{emp}", method = RequestMethod.DELETE)
	public ResponseEntity<?> removeEmployee(@PathVariable("emp") int empid) {
		if(empid < 0) {
			return new ResponseEntity<String>("Employee Id is not valid.", HttpStatus.BAD_REQUEST);
		}

		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee emp = (Employee) iterator.next();
			if(emp.getEmpId()==empid) {
				iterator.remove();
		        return new ResponseEntity<String>("Employee Successfully removed.", HttpStatus.OK);
			}
		}
		return new ResponseEntity<String>("Employee Not found.", HttpStatus.NOT_FOUND);
	}

	@RequestMapping(value = "/addEmp", 
			method = RequestMethod.POST)
	public ResponseEntity<?> addEmployee(@RequestBody Employee emp) {

		if(emp.getEmpId() < 0) {
			return new ResponseEntity<String>("Employee Id is not valid.", HttpStatus.BAD_REQUEST);
		}

		if(StringUtils.isBlank(emp.getDeptName())) {
			return new ResponseEntity<String>("Department name is not valid.", HttpStatus.BAD_REQUEST);
		}

		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee tempEmp = (Employee) iterator.next();
			if(tempEmp.getEmpId()==emp.getEmpId()) {
				return new ResponseEntity<String>("Employee already present. No need to add again", HttpStatus.OK);
			}
		}
		list.add(emp);
		return new ResponseEntity<String>("Employee Successfully Added", HttpStatus.OK);
	}

	@RequestMapping(value = "/updateEmp", 
			method = RequestMethod.PUT)
	public ResponseEntity<?> updateEmployee(@RequestBody Employee emp) {
		if(emp.getEmpId() < 0) {
			return new ResponseEntity<String>("Employee Id is not valid.", HttpStatus.BAD_REQUEST);
		}

		if(StringUtils.isBlank(emp.getDeptName())) {
			return new ResponseEntity<String>("Department name is not valid.", HttpStatus.BAD_REQUEST);
		}
		
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee tempEmp = (Employee) iterator.next();
			if(tempEmp.getEmpId()==emp.getEmpId()) {
				tempEmp.setDeptName(emp.getDeptName());
				return new ResponseEntity<String>("Employee Successfully updated", HttpStatus.OK);
			}
		}
		return new ResponseEntity<String>("Employee Not found.", HttpStatus.NOT_FOUND);
	}

	@ExceptionHandler
	public ResponseEntity<String> exceptionHandler(Exception e){
		e.printStackTrace();
		return new ResponseEntity<String>("An internal error occurred while processing your request.", HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

Tips for fault handling in REST web services

  • Validate the input received from the request and make sure to return appropriate response message and failure HTTP response code.
  • If operation was successful then send a success message and success HTTP response code.
  • In case of any exception, the ExceptionHandler method shall get invoked and return an INTERNAL_SERVER_ERROR HTTP response code (500).
  • Use application logging to troubleshoot and fix issues not yet captured by code.

Download application WAR

The complete REST web service application with proper error and handling code can be downloaded from following link:

After deploying the above application, you can perform CRUD operations on REST url’s by using the methods provided in REST web service beginners tutorial.

Related Posts

Error handling in Spring REST web services admin Spring
The best part of Spring framework is that it address all issues about which an application developer will be concerned. One such concern for developers is error handling or exception handling in web based applications and web services. There is very innovative way in which error/exception handlers can be...
The best part of Spring framework is that it address all issues about which an application developer will be concerned. One such concern for developers is error handling or exception handling in web based applications and web services. There is very innovative way in which error/exception handlers can be configured in a Spring controller. The error handler is automatically invoked in case of any exception without each individual method requiring to introduce boilerplate try-catch or repetitive code. We shall this being implemented for Spring based web services, but <strong>this practices listed here should be followed by web services implemented using any framework/platform</strong>. The underlying thought is to make the web service client aware of proper error message and HTTP response code. <h2>Demo URL's</h2> Let us first start with the demo. Click on each of the following demo buttons to see what you will achieve: <h3>Success response from web service</h3> <a rel="nofollow" target="_new" href="http://springrswebserviceerrorhandling.extremejava.cloudbees.net/services/getEmp/1"><img src="http://www.javaexperience.com/wp-content/uploads/2012/12/demo.jpg"/></a> <h3>Error response from web service</h3> <a rel="nofollow" target="_new" href="http://springrswebserviceerrorhandling.extremejava.cloudbees.net/services/getEmp/1111"><img src="http://www.javaexperience.com/wp-content/uploads/2012/12/demo.jpg"/></a> <h2>Sample Spring controller code</h2> In this tutorial we shall see how to configure exception handler for a RESTful web service application. You need to perform following tasks for proper error handling: <strong>a)</strong> Validate user input. <strong>b</strong>) Do exception handling using ExceptionHandler method in controller code. The code is same from my REST web service beginners tutorial with added error handler method: 1 <h2>Tips for fault handling in REST web services</h2> <ul> <li>Validate the input received from the request and make sure to return appropriate response message and failure HTTP response code.</li> <li>If operation was successful then send a success message and success HTTP response code.</li> <li>In case of any exception, the ExceptionHandler method shall get invoked and return an INTERNAL_SERVER_ERROR HTTP response code (500).</li> <li>Use application logging to troubleshoot and fix issues not yet captured by code.</li> </ul> <h2>Download application WAR</h2> The complete REST web service application with proper error and handling code can be downloaded from following link: <div class="download-code"><img src="http://www.javaexperience.com/wp-content/uploads/2012/10/downloadcode-e1349278942164.jpg"><a href="http://javaexperience.com/wp-content/uploads/2012/12/SpringRSWebServiceErrorHandling.war"><br><br><strong>Spring Web Service Error Handling</strong></a></div> After deploying the above application, you can perform CRUD operations on REST url's by using the methods provided in <a href="http://www.javaexperience.com/spring-restful-web-service-tutorial/">REST web service beginners tutorial</a>.
Adding openID authentication in Spring web application
Enable logging for specific Spring modules
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments