Spring 3 MVC Exception Handling with @ExceptionHandler and @ResponseStatus

@ExceptionHandler : It is method annotation within a controller to specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods.
@ResponseStatus : It marks a method or exception class with the status code and reason that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever said exception is thrown.

Example : will see how these two annotaions work
1. Defined exception class ( will throw from controller)
package com.exception;

public class UserDefinedException extends RuntimeException{

 private static final long serialVersionUID = 1L;
 public String message;
 public UserDefinedException(String message) {
  this.message = message;

 public String getMessage() {
  return message;
package com.controller;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.exception.UserDefinedException;

public class ExceptionDemo {

 public String userDefinedExceptionDemo(){
  boolean exception = true;
   throw new UserDefinedException("exception in controller"); // throw user defined exception
  return "welcome";
 @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user defined response status")
 public void handleUserDefinedException(){

First method :  Whenever user hit the URL ("../welcome") it will throw user defined exception
Second method : - When the exception ( UserDefinedException )occurs in controller, the method will call and will set the response status.


Not defined any exception handling to configuration
if you hit the URL "http://localhost:8080/SpringMVCDemo/welcome" you can see the user defined status on browser.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...