SpringBoot 2.x 统一异常处理

1、统一异常处理类

package cn.hadron.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(HttpServletRequest request,Exception e){
        System.out.println("###出现异常!");
        Map map=new HashMap<>();
        map.put("url",request.getRequestURL().toString());
        map.put("msg",e.getMessage());
        return map;
    }
}

2、异常测试控制器

package cn.hadron.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PathController extends BaseController{

    /**
     * 异常处理测试
     */
    @RequestMapping("/test")
    @ResponseBody
    public String test(String name) throws Exception{
        System.out.println("异常处理测试!");
        if(name==null) {
            throw new Exception("字段空值");
        }
        return "index";
    }

}

3、页面




    
    错误页面
    
                    
                    

你可能感兴趣的:(SpringBoot,2.x学习笔记)