<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2016/03/REST-Spring-Exception-Handling.png" border="0" /></div>
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<h2><b>Table of Contents</b></h2>
<ol style="text-align: left;">
<li><b>Overview</b></li>
<li><b>@ExceptionHandler</b></li>
<li><b>@ControllerAdvice</b></li>
<li><b>ExceptionHandlerResolver</b></li>
<li><b>Handle the Access Denied in Spring Security</b></li>
<li><b>Summ</b>ary</li>
</ol>
<h2><b>1. Overview</b></h2>
<p>Here we are going describe how to implement Exception Handling with Spring for a REST API.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<p><b>Before Spring 3.2</b><br />
There are two main approaches to handling exceptions in a Spring MVC application were: HandlerExceptionResolver or the @ExceptionHandler annotation. Both of these have some clear downsides.</p>
<p><b>After Spring 3.2</b><br />
We now have the new @ControllerAdvice annotation to address the limitations of the previous two solutions.</p>
<p>All of these do have one thing in common – they deal with the <b>separation of concerns </b>very well. The app can throw exception normally to indicate a failure of some kind – exceptions which will then be handled separately.</p>
<h2><b>2. The Controller level using @ExceptionHandler</b></h2>
<p>Here we will define a method to handle exceptions, and annotate that with @ExceptionHandler at the controller level. This solution is limited to the controller only for the same type of exceptions i.e. this approach has a major drawback – the @ExceptionHandler annotated method is only active for that particular Controller, not globally for the entire application. Of course, adding this to every controller makes it not well suited for a general exception handling mechanism.</p>
<p>We can avoid this limitation by making base controller which is extended by every controller in the application however this can be a problem for applications where, for whatever reasons, the Controllers cannot be made to extend from such a class because of this, not a good approach for reducing loose coupling.</p>
</div>
<pre class="highlight">@Controller
public class WebController {
 @ExceptionHandler(StudentNotFoundException.class)
 public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) {
 Map<;String, String>; model = new HashMap<;String, String>;();
 model.put("exception", ex.toString());
 return new ModelAndView("student.error", model);

 }
}
</pre>
<h2><b>3. The New @ControllerAdvice (Spring 3.2 and Above)</b></h2>
<p>From Spring 3.2 offers to global exception handling @ExceptionHandler with the new @ControllerAdvice annotation, this enables a mechanism that breaks away from the older MVC model and makes use of ResponseEntity along with the type safety and flexibility of @ExceptionHandler:</p>
<pre class="highlight">package com.doj.spring.web.controller;

import org.springframework.http.HttpHeaders;
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 org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends
 ResponseEntityExceptionHandler {
 @ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class })
 protected ResponseEntity<;Object>; handleConflict(RuntimeException ex, WebRequest request) {
 String bodyOfResponse = "This should be application specific";
 return handleExceptionInternal(ex, bodyOfResponse, 
 new HttpHeaders(), HttpStatus.CONFLICT, request);
 }
}

</pre>
<p>The new annotation allows the multiple scattered @ExceptionHandler from before to be consolidated into a single, global error handling component.</p>
<p>The actual mechanism is extremely simple but also very flexible:</p>
<ul style="text-align: left;">
<li>it allows full control over the body of the response as well as the status code</li>
<li>it allows mapping of several exceptions to the same method, to be handled together</li>
<li>it makes good use of the newer RESTful ResposeEntity response</li>
</ul>
<p>One thing to keep in mind here is to match the exceptions declared with @ExceptionHandler with the exception used as argument of the method. If these don’t match, the compiler will not complain – no reason it should, and Spring will not complain either.</p>
<h2><b>4. The HandlerExceptionResolver</b></h2>
<p>It will also allow us to implement a uniform exception handling mechanism in our REST API.</p>
<p><b>ExceptionHandlerExceptionResolver</b><br />
<b><br />
</b> This resolver was introduced in Spring 3.1 and is enabled by default in the DispatcherServlet. This is actually the core component of how the @ExceptionHandler mechanism presented earlier works.</p>
<p><b>DefaultHandlerExceptionResolver</b><br />
<b><br />
</b> This resolver was introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes.</p>
<p><b>ResponseStatusExceptionResolver</b></p>
<p>This resolver was also introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It’s main responsibility is to use the @ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.</p>
<pre class="highlight">package com.doj.spring.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found")
public class StudentNotFoundException extends RuntimeException{

 /**
 * 
 */
 private static final long serialVersionUID = -2581975292273282583L;
 
 String errorMessage;
 
 String errorCode;

 public StudentNotFoundException(String errorMessage, String errorCode) {
 super();
 this.errorMessage = errorMessage;
 this.errorCode = errorCode;
 }

 public String getErrorMessage() {
 return errorMessage;
 }

 public void setErrorMessage(String errorMessage) {
 this.errorMessage = errorMessage;
 }

 public String getErrorCode() {
 return errorCode;
 }

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

</pre>
<p>Same as the DefaultHandlerExceptionResolver, this resolver is limited in the way it deals with the body of the response – it does map the Status Code on the response, but the body is still null.</p>
<p><b>Custom HandlerExceptionResolver</b><br />
The combination of DefaultHandlerExceptionResolver and ResponseStatusExceptionResolver goes a long way towards providing a good error handling mechanism for a Spring RESTful Service. The downside is – as mentioned before – no control over the body of the response.</p>
<p>Ideally, we’d like to be able to output either JSON or XML, depending on what format the client has asked for via the Accept header.</p>
<h2><b>5. Handle the Access Denied in Spring Security</b></h2>
<p><b>MVC – Custom Error Page</b><br />
<b>XML configuration:</b></p>
<pre class="highlight"><;http>;
 <;intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>; 
 ... 
 <;access-denied-handler error-page="/custom-error-page" />;
<;/http>;
</pre>
<p><b>Java Configuration:</b></p>
<pre class="highlight">@Override
protected void configure(HttpSecurity http) throws Exception {
 http.authorizeRequests()
 .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
 ...
 .and()
 .exceptionHandling().accessDeniedPage("/custom-error-page");
}
</pre>
<p>When users tries to access a resource without having enough authorities, they will be redirected to &#8220;/custom-error-page&#8221;.</p>
<h2><b>6. Summary</b></h2>
<p>This tutorial discussed several ways to implement an exception handling mechanism for a REST API in Spring.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Spring MVC Related Posts</b></span></p>
<ul>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><span style="color: red;">Spring MVC Web Tutorial</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-mvc-interview-questions-and-answers/"><span style="color: red;">Spring MVC Interview Questions</span></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-mvc/"><span style="color: red;">MVC Design Pattern</span></a></b></li>
<li><b><a href="https://dineshonjava.com/what-is-dispatcherservlet-in-spring-and-its-uses/"><span style="color: red;">Spring MVC DispatcherServlet </span></a></b></li>
<li><b><a href="https://dineshonjava.com/difference-between-applicationcontext-webapplicationcontext-in-spring-mvc/"><span style="color: red;">Spring MVC WebApplicationContext and Root Application Context</span></a></b></li>
<li><b><a href="https://dineshonjava.com/stereotype-annotations-in-spring/"><span style="color: red;">Spring MVC @Controller Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestmapping-annotation-in-spring-mvc/"><span style="color: red;">Spring MVC @RequestMapping Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestparam-annotation-in-spring-mvc-with-example/"><span style="color: red;">Spring MVC @RequestParam Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/difference-between-applicationcontext-webapplicationcontext-in-spring-mvc/"><span style="color: red;">Spring MVC ContextLoaderListener</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestparam-vs-pathvariable-annotations-in-spring-mvc/"><span style="color: red;">Spring MVC @RequestParam and @PathVariable annotations</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-30-mvc-hello-world-example/"><span style="color: red;">Spring MVC Hello World Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-exception-handling-example/"><span style="color: red;">Spring MVC Exception Handling Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-mvc-with-hibernate-crud-example/"><span style="color: red;">Spring MVC with Hibernate CRUD Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-tiles-plugin-with-example/"><span style="color: red;">Spring MVC Tiles Plugin with Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-and-interceptor-with/"><span style="color: red;">Spring MVC Interceptor with example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/integration-spring-mvc3-and-mongodb/"><span style="color: red;">Spring MVC with MongoDB CRUD Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-internationalization/"><span style="color: red;">Spring MVC Internationalization &; Localization with Example</span></a></b></li>
</ul>
</div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/requestmapping-annotation-in-spring-mvc/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/method-injection-with-spring-using-lookup-method-property/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '151'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…