Spring MVC @ExceptionHandler Exemple

Exemple Spring MVC @ExceptionHandler

Dans ce didacticiel, nous vous montrons comment gérer les exceptions dans les frameworks Spring MVC. Normalement, nous utilisons@ExceptionHandler pour décider quelle «vue» doit être renvoyée si une exception est levée.

P.S This @ExceptionHandler class is available since Spring 3.0

1. Structure du projet

Passez en revue la structure du répertoire du projet, un projet Maven standard.

directory structure

2. Exception personnalisée

Une exception personnalisée, avec un code d'erreur et une description d'erreur personnalisés.

CustomGenericException.java

package com.example.web.exception;

public class CustomGenericException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private String errCode;
    private String errMsg;

    public String getErrCode() {
        return errCode;
    }

    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public CustomGenericException(String errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

}

3. Contrôleur de printemps

Un contrôleur Spring, passez en revue les flux d'exécution ci-dessous:

  1. Si l'utilisateur fournit une requête/error, il lance «CustomGenericException» et la méthodehandleCustomException() sera déclenchée.

  2. Si l'utilisateur fournit une requête/io-error, il lance «IOException» et la méthodehandleAllException() sera déclenchée.

MainController.java

package com.example.web.controller;

import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.example.web.exception.CustomGenericException;

@Controller
public class MainController {

    @RequestMapping(value = "/{type:.+}", method = RequestMethod.GET)
    public ModelAndView getPages(@PathVariable("type") String type)
        throws Exception {

      if ("error".equals(type)) {
        // go handleCustomException
        throw new CustomGenericException("E888", "This is custom message");
      } else if ("io-error".equals(type)) {
        // go handleAllException
        throw new IOException();
      } else {
        return new ModelAndView("index").addObject("msg", type);
      }

    }

    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomException(CustomGenericException ex) {

        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errCode", ex.getErrCode());
        model.addObject("errMsg", ex.getErrMsg());

        return model;

    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllException(Exception ex) {

        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errMsg", "this is Exception.class");

        return model;

    }

}

4. Pages JSP

pages/index.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


    

Spring MVC @ExceptionHandler Example

${msg}

pages/error/generic_error.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>



    
        

${errCode} : System Errors

System Errors

${errMsg}

6. Exemple @ControllerAdvice

L'exemple de@ExceptionHandler ci-dessus ne s'applique qu'à un seul contrôleur, pour l'appliquer globalement (tous les contrôleurs), annoter une classe avec@ControllerAdvice.

GlobalExceptionController.java

package com.example.web.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import com.example.web.exception.CustomGenericException;

@ControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomException(CustomGenericException ex) {

        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errCode", ex.getErrCode());
        model.addObject("errMsg", ex.getErrMsg());

        return model;

    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllException(Exception ex) {

        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errMsg", "this is Exception.class");

        return model;

    }

}

7. Télécharger le code source