Spring Rest service – Exception handling


Exception Handling in Spring Rest service

We have seen Exception handling in Spring MVC in this and this article.

It is very similar in Spring Rest service also to handle the exception but the main difference is, In Spring MVC we will return error view page to the client where as in Spirng Rest service we need to send the error response with appropriate format so that the consumer of the Rest service will get a clear information about the response status and can proceed further.

Create a new Maven Web project in eclipse (Refer Spring MVC Hello World project for the same)

Project structure


RestExceptionHandlerProjStructure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>SpringRestExceptionHandling</groupId>
  5.   <artifactId>SpringRestExceptionHandling</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringRestExceptionHandling Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <!-- Jackson JSON -->
  32.         <dependency>
  33.             <groupId>com.fasterxml.jackson.core</groupId>
  34.             <artifactId>jackson-databind</artifactId>
  35.             <version>2.8.5</version>
  36.         </dependency>
  37.   </dependencies>
  38.   <build>
  39.     <finalName>SpringRestExceptionHandling</finalName>
  40.   </build>
  41. </project>
<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>SpringRestExceptionHandling</groupId>
  <artifactId>SpringRestExceptionHandling</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestExceptionHandling Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<!-- Jackson JSON -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
		</dependency>
  </dependencies>
  <build>
    <finalName>SpringRestExceptionHandling</finalName>
  </build>
</project>

We have added dependencies for Spring web ,spring web mvc,Jackson and Junit in the above pom file.

Step 2

Update web.xml file with Dispatcher servlet

we have defined a dispatcher servlet in web.xml and mapped it by the URL pattern “/”

So just like any other servlet in web application,any request matching with the given pattern i.e “/” will be redirected to “Dispatcher servlet”.

  1. <web-app id="WebApp_ID" version="2.4"
  2.     xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  4. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  5.  
  6.     <display-name>Archetype Created Web Application</display-name>
  7.     <servlet>
  8.         <servlet-name>mvc-dispatcher</servlet-name>
  9.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10.         <init-param>
  11.             <param-name>contextConfigLocation</param-name>
  12.             <param-value>
  13.             /WEB-INF/spring-mvc.xml
  14.             </param-value>
  15.         </init-param>
  16.         <load-on-startup>1</load-on-startup>
  17.     </servlet>
  18.  
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <context-param>
  25.         <param-name>contextConfigLocation</param-name>
  26.         <param-value>/WEB-INF/spring-mvc.xml</param-value>
  27.     </context-param>
  28.  
  29.     <listener>
  30.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  31.     </listener>
  32. </web-app>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Archetype Created Web Application</display-name>
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
            /WEB-INF/spring-mvc.xml
            </param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-mvc.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

We have also provided the spring configuration file name to create and load the spring beans while starting the server.

Step 3

Create a spring config file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-4.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.rest" />
  14.     <mvc:annotation-driven />
  15.      
  16. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
 
    <context:component-scan base-package="com.kb.rest" />
    <mvc:annotation-driven />
     
</beans>

we have defined the base package as “com.kb.rest” so that anything inside this package will be eligible to become spring bean.

Step 4

Create a domain class which represents the data in JSON format

  1. package com.kb.rest.model;
  2.  
  3. public class User {
  4.     private String name;
  5.     private int age;
  6.     private int id;
  7.     public String getName() {
  8.         return name;
  9.     }
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.     public void setAge(int age) {
  17.         this.age = age;
  18.     }
  19.     public int getId() {
  20.         return id;
  21.     }
  22.     public void setId(int id) {
  23.         this.id = id;
  24.     }
  25.  
  26. }
package com.kb.rest.model;

public class User {
	private String name;
	private int age;
	private int id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

}

We have created a User class with id,name and age to represent the data

Step 5

Create a rest service controller class

  1. package com.kb.rest.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8.  
  9. import com.kb.rest.model.User;
  10.  
  11. @Controller
  12. @RequestMapping("/user")
  13. public class RestController {
  14.  
  15.     @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
  16.     public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
  17.         User user = new User();
  18.         user.setId(id);
  19.         user.setName("John");
  20.         user.setAge(45);
  21.         if(id !=1){
  22.             throw new RuntimeException();
  23.         }
  24.        
  25.         return user;
  26.     }
  27. }
package com.kb.rest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kb.rest.model.User;

@Controller
@RequestMapping("/user")
public class RestController {

	@RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
	public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
		User user = new User();
		user.setId(id);
		user.setName("John");
		user.setAge(45);
		if(id !=1){
			throw new RuntimeException();
		}
		
		return user;
	}
}

In the above Rest service, we are throwing exception if the user id is anything other than 1 and there is no handler defined.

Step 6

Deploy the code and try to access the user with id 2

http://localhost:8080/SpringRestExceptionHandling/user/getSpecificUser/2

RestWithoutExceptionHandler

Now client does not know how to handle this exception as it does not have any information about it.
Hence we can see the exception stack trace at the client side.


Now let’s write a Rest Service which can handle the exception

Step 7


Create a custom exception class

  1. package com.kb.rest.exception;
  2.  
  3. public class UserNotFoundException extends Exception {
  4.     private static final long serialVersionUID = 1L;
  5.     private String errorMessage;
  6.  
  7.     public UserNotFoundException() {
  8.         super();
  9.     }
  10.  
  11.     public UserNotFoundException(String errorMessage) {
  12.         super(errorMessage);
  13.         this.errorMessage = errorMessage;
  14.     }
  15.  
  16.     public String getErrorMessage() {
  17.         return errorMessage;
  18.     }
  19.  
  20. }
package com.kb.rest.exception;

public class UserNotFoundException extends Exception {
	private static final long serialVersionUID = 1L;
	private String errorMessage;

	public UserNotFoundException() {
		super();
	}

	public UserNotFoundException(String errorMessage) {
		super(errorMessage);
		this.errorMessage = errorMessage;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

}

We have created a custom exception class with errorMessage property.

Step 8

Create error response class

  1. package com.kb.rest.error;
  2.  
  3. public class UserErrorResponse {
  4.     private int errorCode;
  5.     private String errorMessage;
  6.    
  7.     public int getErrorCode() {
  8.         return errorCode;
  9.     }
  10.     public void setErrorCode(int errorCode) {
  11.         this.errorCode = errorCode;
  12.     }
  13.     public String getErrorMessage() {
  14.         return errorMessage;
  15.     }
  16.     public void setErrorMessage(String errorMessage) {
  17.         this.errorMessage = errorMessage;
  18.     }
  19.  
  20. }
package com.kb.rest.error;

public class UserErrorResponse {
	private int errorCode;
	private String errorMessage;
	
	public int getErrorCode() {
		return errorCode;
	}
	public void setErrorCode(int errorCode) {
		this.errorCode = errorCode;
	}
	public String getErrorMessage() {
		return errorMessage;
	}
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

}


There are 2 ways to handle the exception in Rest service


1) Controller based Exception handler
2) Global exception handler


1) Controller based Exception handler

In this type of Exception handling, we can write handler methods inside the controller class itself.
So to achive this , we need to
a) Define a new method inside the controller
b) Annotate this mehod with @ExceptionHandler and parameter as Exception that we have to handle
c) Handle the Exception inside this method and return the response in the required format.

Limitation of this approach is that , only those exceptions which are thrown inside this controller class can be handled.

Any exceptions thrown from outside this controller class will be left unhandled and same exception stack trace will be sent to client side.

Step 9

Create a Rest service which can have Controller based exception handling

  1. package com.kb.rest.controllers;
  2.  
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11.  
  12. import com.kb.rest.error.UserErrorResponse;
  13. import com.kb.rest.exception.UserNotFoundException;
  14. import com.kb.rest.model.User;
  15.  
  16. @Controller
  17. @RequestMapping("/user/controllerExceptionHandler")
  18. public class RestServiceControllerExceptionHandling {
  19.  
  20.     @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
  21.     public @ResponseBody ResponseEntity<User> getUserForId(@PathVariable("id") int id) throws UserNotFoundException {
  22.         User user = new User();
  23.         user.setId(id);
  24.         user.setName("John");
  25.         user.setAge(45);
  26.         if (id != 1) {
  27.             throw new UserNotFoundException("User not found");
  28.         }
  29.  
  30.         return new ResponseEntity<User>(user, HttpStatus.OK);
  31.  
  32.     }
  33.  
  34.     @ExceptionHandler(UserNotFoundException.class)
  35.     public ResponseEntity<UserErrorResponse> handleUserNotFoundException(Exception ex) {
  36.         UserErrorResponse errorResponse = new UserErrorResponse();
  37.         errorResponse.setErrorCode(HttpStatus.PRECONDITION_FAILED.value());
  38.         errorResponse.setErrorMessage(ex.getMessage());
  39.         return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
  40.     }
  41.  
  42. }
package com.kb.rest.controllers;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kb.rest.error.UserErrorResponse;
import com.kb.rest.exception.UserNotFoundException;
import com.kb.rest.model.User;

@Controller
@RequestMapping("/user/controllerExceptionHandler")
public class RestServiceControllerExceptionHandling {

	@RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<User> getUserForId(@PathVariable("id") int id) throws UserNotFoundException {
		User user = new User();
		user.setId(id);
		user.setName("John");
		user.setAge(45);
		if (id != 1) {
			throw new UserNotFoundException("User not found");
		}

		return new ResponseEntity<User>(user, HttpStatus.OK);

	}

	@ExceptionHandler(UserNotFoundException.class)
	public ResponseEntity<UserErrorResponse> handleUserNotFoundException(Exception ex) {
		UserErrorResponse errorResponse = new UserErrorResponse();
		errorResponse.setErrorCode(HttpStatus.PRECONDITION_FAILED.value());
		errorResponse.setErrorMessage(ex.getMessage());
		return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
	}

}

we have defined the Rest Service with Controller Exception Handling.

we are throwing the UserNotFoundException when user id is anything other than 1.
and there is a handler method in the controller which is handling this exception and returning a response with valid error code and error message.

Step 10

Deploy the code and try to access the user with id 2

http://localhost:8080/SpringRestExceptionHandling/user/controllerExceptionHandler/getSpecificUser/2

ControllerBasedHandler

we can see that error code and error message sent to the client, Now client can easily understand the exception and proceed further.


2) Global Exception handler

In this approach , the implementation is almost similar to @ExceptionHandler approach only.
The only difference here is that , it can handle all the exceptions thrown from any of the controllers in the application.

So it is always advisable to use this approach.

It can be implemented as
a) Define a new class and annotate this class with @ControllerAdvice
b) Keep on adding new method for each exception using @ExceptionHandler annotation.

So class which is annotated with @ControllerAdvice is considered as global exception handler because methods inside it can handle the exception thrown from any controller in the application.

Step 11


Create a Rest service which throws exception in some scenario

  1. package com.kb.rest.controllers;
  2.  
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10.  
  11. import com.kb.rest.exception.UserNotFoundException;
  12. import com.kb.rest.model.User;
  13.  
  14. @Controller
  15. @RequestMapping("/user/globalExceptionHandler")
  16. class RestServiceGlobalExceptionHandling {
  17.  
  18.     @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
  19.     public @ResponseBody ResponseEntity<User> getUserForId(@PathVariable("id") int id) throws Exception {
  20.         User user = new User();
  21.         user.setId(id);
  22.         user.setName("John");
  23.         user.setAge(45);
  24.         if (id != 1) {
  25.             throw new UserNotFoundException("User not found");
  26.         }
  27.  
  28.         // Intentionally throwing exception
  29.         int ageByZero = user.getAge() / 0;
  30.  
  31.         user.setAge(ageByZero);
  32.         return new ResponseEntity<User>(user, HttpStatus.OK);
  33.  
  34.     }
  35.  
  36. }
package com.kb.rest.controllers;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kb.rest.exception.UserNotFoundException;
import com.kb.rest.model.User;

@Controller
@RequestMapping("/user/globalExceptionHandler")
class RestServiceGlobalExceptionHandling {

	@RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<User> getUserForId(@PathVariable("id") int id) throws Exception {
		User user = new User();
		user.setId(id);
		user.setName("John");
		user.setAge(45);
		if (id != 1) {
			throw new UserNotFoundException("User not found");
		}

		// Intentionally throwing exception
		int ageByZero = user.getAge() / 0;

		user.setAge(ageByZero);
		return new ResponseEntity<User>(user, HttpStatus.OK);

	}

}

we have defined the Rest Service which can throw multiple exceptions.

In this service,we are throwing the UserNotFoundException when user id is anything other than 1.
We are also intentionally throwing Divide by Zero Arithmetic exception when user id is 1

Step 12

Create a global exception handler class

  1. package com.kb.rest.handler;
  2.  
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.web.bind.annotation.ControllerAdvice;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import com.kb.rest.error.UserErrorResponse;
  8. import com.kb.rest.exception.UserNotFoundException;
  9.  
  10. @ControllerAdvice  
  11. public class UserExceptionHandler {
  12.    
  13.     @ExceptionHandler(UserNotFoundException.class)
  14.     public ResponseEntity<UserErrorResponse> handleUserNotFoundException(Exception ex) {
  15.         UserErrorResponse errorResponse = new UserErrorResponse();
  16.         errorResponse.setErrorCode(HttpStatus.PRECONDITION_FAILED.value());
  17.         errorResponse.setErrorMessage(ex.getMessage());
  18.         return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
  19.     }
  20.    
  21.     @ExceptionHandler(Exception.class)
  22.     public ResponseEntity<UserErrorResponse> handleGenericException(Exception ex) {
  23.         UserErrorResponse errorResponse = new UserErrorResponse();
  24.         errorResponse.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
  25.         errorResponse.setErrorMessage("There is some techncal issue");
  26.         return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
  27.     }
  28.  
  29. }
package com.kb.rest.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.kb.rest.error.UserErrorResponse;
import com.kb.rest.exception.UserNotFoundException;

@ControllerAdvice	
public class UserExceptionHandler {
	
	@ExceptionHandler(UserNotFoundException.class)
	public ResponseEntity<UserErrorResponse> handleUserNotFoundException(Exception ex) {
		UserErrorResponse errorResponse = new UserErrorResponse();
		errorResponse.setErrorCode(HttpStatus.PRECONDITION_FAILED.value());
		errorResponse.setErrorMessage(ex.getMessage());
		return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
	}
	
	@ExceptionHandler(Exception.class)
	public ResponseEntity<UserErrorResponse> handleGenericException(Exception ex) {
		UserErrorResponse errorResponse = new UserErrorResponse();
		errorResponse.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		errorResponse.setErrorMessage("There is some techncal issue");
		return new ResponseEntity<UserErrorResponse>(errorResponse, HttpStatus.OK);
	}

}

This exception handler class will handle the exceptions thrown in any of the controller

It has 2 handler methods one for handling UserNotFoundException and another one for handling Generic exception

Step 13

Deploy the code and try to access the user with id 2

http://localhost:8080/SpringRestExceptionHandling/user/globalExceptionHandler/getSpecificUser/2

GlobalExceptionHandler1

we can see that meaningful error code and error message sent to the client, Now client can easily understand the exception and proceed further.

Access the below url which will throw Divide by Zero Arithmetic exception

http://localhost:8080/SpringRestExceptionHandling/user/globalExceptionHandler/getSpecificUser/1

GlobalExceptionHandler2

Here also we can see that meaningful error code and error message sent to the client, Now client can easily understand the exception and proceed further.

Download this project SpringRestExceptionHandling.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on