SpringBoot 2.0 Base Case (03): Configure system global exception mapping handling

1. Classification of Exceptions

From the point of view of handling exceptions by the system, there are two main categories of exceptions: business exceptions and system exceptions.

1. Business Exceptions

Business exceptions are mainly some predictability exceptions. Handle business exceptions to prompt users for operation and improve the operability of the system.
Common business exception tips:
1) Please enter xxx
2)xxx cannot be empty
3)xxx duplicate, please replace

2. System Exceptions

System exceptions are mainly some unpredictable exceptions. Handling system exceptions can show a friendly user interface and not easily offend users.If it is a financial system, there is a system abnormal crash interface in the user interface, which is likely to directly lead to user loss.
Common system exception tips:
1) Page loss 404
2) Server exception 500

2. Solve 404 interface after application start-up

1. Introducing Page Jar Package

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. Customize Home Page Interface

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
    @RequestMapping("/")
    public String index(ModelMap modelMap) {
        modelMap.addAttribute("name","Know a smile") ;
        return "index";
    }
}

3. Home page interface

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${name}"></h1>
</body>
</html>

4. Operation effect

3. Exception handling in SpringBoot 2.0

1. Project Structure Diagram

2. Customize Business Exception Class

public class ServiceException extends Exception {
    public ServiceException (String msg){
        super(msg);
    }
}

3. Custom Exception Description Object

public class ReturnException {
    // Response Code
    private Integer code;
    // Exception Description
    private String msg;
    // Requested Url
    private String url;
    // Omit get set method
}

4. Unified exception handling format

1) Two basic notes
@ControllerAdvice defines a uniform exception handling class
@ExceptionHandler defines how exception types are handled
2) Code implementation

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
// Exception returns the same ExceptionHandler + ResponseBody comment in Json format
// @RestControllerAdvice
public class HandlerException {
    /**
     * Customize business exception mapping, return JSON format prompt
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public ReturnException handler01 (HttpServletRequest request,ServiceException e){
        ReturnException returnException = new ReturnException() ;
        returnException.setCode(600);
        returnException.setMsg(e.getMessage());
        returnException.setUrl(String.valueOf(request.getRequestURL()));
        return returnException ;
    }
    /**
     * Service Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView handler02 (HttpServletRequest request,Exception e){
        ModelAndView modelAndView = new ModelAndView() ;
        modelAndView.addObject("ExeMsg", e.getMessage());
        modelAndView.addObject("ReqUrl", request.getRequestURL());
        modelAndView.setViewName("/exemsg");
        return modelAndView ;
    }
}

5. Simple test interface

@Controller
public class ExeController {
    /**
     *  {
     *    "code": 600,
     *    "msg": "Business exception: ID cannot be empty.
     *    "url": "http://localhost:8003/exception01"
     *  }
     */
    @RequestMapping("/exception01")
    public String exception01 () throws ServiceException {
        throw new ServiceException("Business exceptions: ID Cannot be empty");
    }

    @RequestMapping("/exception02")
    public String exception02 () throws Exception {
        throw new Exception("Abnormal, all lying down");
    }
}

4. Source code address

GitHub Address: Know a smile
https://github.com/cicadasmile
 Code Cloud Address: Know a smile
https://gitee.com/cicadasmile

Tags: Java JSON github Spring Thymeleaf

Posted on Fri, 09 Aug 2019 11:18:33 -0700 by wilburforce