SpringBoot:捕获全局异常并处理

一,基于SpringBoot提供的@ControllerAdvice全局异常捕获。

    1,异常演示代码,此处通过传参,手动制造一个by zero异常

package springboot.test2.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pj_zhang
 * @create 2018-12-23 23:06
 **/
@RestController
public class ErrorController {

    @RequestMapping("/calculate")
    public String calculate(int i) {
        int j = 6 / i;
        return String.valueOf(j);
    }
}

    2,异常处理类

package springboot.test2.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import springboot.test2.controller.ErrorController;

/**
 * @author pj_zhang
 * @create 2018-12-23 23:12
 **/
// SpringBoot捕获全局异常提供的支持注解
@ControllerAdvice
public class ErrorHandler {

    // 使用log4j进行日志记录, 模拟正式环境
    private final Logger logger = LoggerFactory.getLogger(ErrorController.class);

    // 异常处理类型, 后面参数为异常级别, 此处表示处理所有异常
    @ExceptionHandler(Exception.class)
    public String error(Exception ex) {
        // 打印异常
        logger.info(ex.getMessage(), ex);
        // 直接返回到错误界面, 正式环境可能存在动静分离, 此处需要封装VO处理
        return "error/fail.html";
    }
}

    3,错误页面信息

    4,异常演示

        * 正常功能

        * 异常功能

猜你喜欢

转载自blog.csdn.net/u011976388/article/details/85227807