Home Spring Spring3.2 @ExceptionHandler & @ResponseStatus annotation



@ExceptionHandler & @ResponseStatus annotation
Posted on: January 12, 2013 at 12:00 AM
In this section, you will learn about @ExceptionHandler & @ResponseStatus annotation.

@ExceptionHandler & @ResponseStatus annotation

In this section, you will learn about @ExceptionHandler & @ResponseStatus annotation.

In Spring, during controller execution, HandlerExceptionResolver implementation manages unexpected exceptions. HandlerExceptionResolver looks very similar to the exception mappings of web.xml. Even so they are more flexible when dealing so. For example, when an exception was thrown, which handler was executing ?-kind of information is provided by HandlerExceptionResolver .

Implementation of both interfaces HandlerExceptionResolver and SimpleMappingExceptionResolver will allow you , declaratively, to map Exceptions to specific views with some nonmandatory Java logic.

The @ExceptionHandler annotation should be used on methods which are called to handle exception. It can be defined locally inside an @Controller or within an @ControllerAdvice class to apply it globally to all @RequestMapping methods.

Given below a sample @ExceptionHandler method:

@Controller
public class SimpleController {
	....................
	....................
	....................
	
	@ExceptionHandler(IOException.class)
	public ResponseEntity<String> handleIOException(IOException ex) {
	
		// prepare responseEntity
		
		return responseEntity;
	}

}

An array of exception types can be supply to @ExceptionHandler. If the value is not set to @RequestMapping annotation then the method arguments type , which is an exception type, is used.

Exceptions With @ResponseStatus

The @ResponseStatus annotation is annotated on business exceptions. As the exception occurs the ResponseStatusExceptionResolver handles it by setting the status of the response according to the exception. The ResponseStatusExceptionResolver is by default registered by the DispatcherServlet.

 

Related Tags for @ExceptionHandler & @ResponseStatus annotation:


More Tutorials from this section

Ask Questions?    Discuss: @ExceptionHandler & @ResponseStatus annotation  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.