Spring Boot 10-SpringBoot全局异常捕获

全局异常拦截
@ControllerAdvice作为全局异常处理的切面类。
@ExceptionHandler(RuntimeException.class)表示拦截异常。
@ResponseBody+Model json返回。效果图如下

package com.tzp.exception.controller;

import java.util.HashMap;
import java.util.Map;

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

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String,Object> exceptionHandler(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("errorCode", "101");
        map.put("errorMsg", "系统错误");
        return map;
    }
    
}
 返回String,效果如下图
package com.tzp.exception.controller;

import java.util.HashMap;
import java.util.Map;

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

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(RuntimeException.class)
    public String exceptionHandler(){
        return "exceptionYM";
    }
    
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>页面异常,请联系管理员。</h1>
</body>
</html>
返回modelAndView,效果

 
package com.tzp.exception.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.ui.Model;
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;

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(RuntimeException.class)
    public ModelAndView exceptionHandler(Model model){
        model.addAttribute("error", "系统错误,请联系管理员!");
        return new ModelAndView("exceptionYMT","errorMap",model);
    }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1 th:text="${errorMap.error}"></h1>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/zengpingtang/p/10816775.html