Home  >  Spring 4

Spring 4 MVC Rest Web Service Exception Handling with @RestController Example

By Arvind Rai, April 10, 2015
In this page we will learn spring 4 MVC Rest Web Service exception handling with @RestController. Spring provides @ExceptionHandler annotation using which we create handler method in controller class for a given exception type. Controller class will be annotated with @RestController annotation. When exception is thrown in application, the exception handler method handles it and collect the information in java bean and respond it. There are different ways to handle exception in spring, to know more we should go through the URL. Here we will provide how to return the error message in REST web services. For our demo, we will use Jackson JSON API.

Project Structure in Eclipse

Find the demo project structure in eclipse.
Spring 4 MVC Rest Web Service Exception Handling  with @RestController  Example

Gradle File to Resolve JAR Dependencies

Find the Gradle file to resolve JAR dependencies.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web:1.2.2.RELEASE'
	compile 'jstl:jstl:1.2'
	providedCompile 'org.springframework.boot:spring-boot-starter-tomcat:1.2.2.RELEASE'
	compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
} 

Java Bean for Error Message

We have created a Java bean to populate error information.
ErrorDetail.java
package com.concretepage.bean;
public class ErrorDetail {
	private int status;
	private String message;
	private String url;
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
} 

Controller using @RestController and @ExceptionHandler

Create a controller annotated with @RestController. It is the combination of @Controller and @ResponseBody. To handle an exception, we need to create an exception method annotated with @ExceptionHandler. This method will return java bean as JSON with error info.
KeywordController.java
package com.concretepage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.concretepage.bean.ErrorDetail;
import com.concretepage.exception.KeywordNotFoundException;
@RestController
@RequestMapping("/keyword")
public class KeywordController {
	@ExceptionHandler(KeywordNotFoundException.class)
	public ErrorDetail myError(HttpServletRequest request, Exception exception) {
	    ErrorDetail error = new ErrorDetail();
	    error.setStatus(HttpStatus.BAD_REQUEST.value());
	    error.setMessage(exception.getLocalizedMessage());
	    error.setUrl(request.getRequestURL().append("/error/111").toString());
	    return error;
	}
	@RequestMapping("/info")
        public String info(@RequestParam(value="key") String key, Model model) {
	    if (!"key101".equals(key)) {
		throw new KeywordNotFoundException(key);
	    }
            return "success";
       }
} 

Create Custom Exception Class

For the demo, we have created our custom exception, if this exception is thrown, it will be caught by our exception handler method defined in controller and java bean for error will be populated and response will be as JSON.
KeywordNotFoundException.java
package com.concretepage.exception;
public class KeywordNotFoundException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	public KeywordNotFoundException(String key){
		super(key+" not available");
	}
} 

Output

To check the output , deploy the code and run the URL http://localhost:8080/concretepage-1/keyword/info?key=key111 , Output will be JSON response.
{"status":400,"message":"key111 not available","url":"http://localhost:8080/concretepage-1/keyword/info/error/111"}
 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus







Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us