Spring Boot 全局异常配置

Spring Boot 全局异常配置,处理异常控制器需要和发生异常的方法在一个类中。使用 ControllerAdvice 注解

package com.li.controller;

import org.springframework.stereotype.Controller;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExceptionHandlerController {
    @RequestMapping("/exceptionTest")
    @ResponseBody
    public String test() throws Exception{
        System.out.println("测试");
        int i=1/0;
        return Integer.toString(i);
    }
    @ControllerAdvice
    class HandlerException{
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public String defultExcepitonHandler(Exception e) {
    //        return "{\"error\":\"error\"}";
            return "error";
        }
    }
}

https://blog.csdn.net/qq_34083066/article/details/79424142

猜你喜欢

转载自www.cnblogs.com/liyafei/p/9179225.html