Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Exception Handling in Spring MVC

Exception handling in Spring MVC involves managing and processing exceptions that occur during the execution of a web request. This guide covers the key concepts and techniques for implementing exception handling in Spring MVC, including using the @ExceptionHandler annotation, the @ControllerAdvice annotation, and custom exception handlers.

Key Concepts of Exception Handling

  • @ExceptionHandler: Handles exceptions thrown by request handling methods in the same controller.
  • @ControllerAdvice: A specialization of the @Component annotation for handling exceptions across the whole application.
  • ResponseEntityExceptionHandler: A convenient base class for controller advice classes that wish to provide centralized exception handling across all request mappings.

Using @ExceptionHandler

The @ExceptionHandler annotation is used to define a method that handles exceptions thrown by request handling methods in the same controller:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @GetMapping("/causeError")
    public String causeError() {
        throw new RuntimeException("An error occurred");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleException(RuntimeException e) {
        return "Handled exception: " + e.getMessage();
    }
}

Using @ControllerAdvice

The @ControllerAdvice annotation is used to define a class that handles exceptions across the whole application:

Example:

// GlobalExceptionHandler.java
package com.example.springmvc.handlers;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(Exception e) {
        return "Global exception handler: " + e.getMessage();
    }
}

Custom Exception Handling

You can create custom exception handlers by extending ResponseEntityExceptionHandler:

CustomExceptionHandler.java

// CustomExceptionHandler.java
package com.example.springmvc.handlers;

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 CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    protected ResponseEntity handleRuntimeException(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This is a custom error message";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
}


        

Displaying Error Pages

You can configure Spring to display custom error pages for specific HTTP status codes by defining error pages in the web.xml file:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/views/error/404.jsp</location>
    </error-page>

    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/views/error/500.jsp</location>
    </error-page>

</web-app>

404.jsp

<html>
<head>
    <title>Error 404</title>
</head>
<body>
    <h1>Error 404: Page not found</h1>
</body>
</html>

500.jsp

<html>
<head>
    <title>Error 500</title>
</head>
<body>
    <h1>Error 500: Internal server error</h1>
</body>
</html>

Key Points

  • @ExceptionHandler: Handles exceptions thrown by request handling methods in the same controller.
  • @ControllerAdvice: Handles exceptions across the whole application.
  • ResponseEntityExceptionHandler: A base class for centralized exception handling.
  • Use @ExceptionHandler to handle exceptions in a specific controller.
  • Use @ControllerAdvice to handle exceptions globally across the application.
  • Create custom exception handlers by extending ResponseEntityExceptionHandler.
  • Configure custom error pages for specific HTTP status codes in the web.xml file.

Conclusion

Exception handling in Spring MVC involves managing and processing exceptions that occur during the execution of a web request. By using the @ExceptionHandler and @ControllerAdvice annotations, as well as creating custom exception handlers, developers can provide a robust and user-friendly error handling mechanism in their Spring MVC applications. Happy coding!