SpringBoot (十) 全局异常捕获

1 测试类

/*
 * @Author  : 有勇气的牛排(全网同名)
 * @FileName: MyIndex.java
 * desc     :
 * */

package couragesteak.service;

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

@RestController
public class MyIndexService {
    
    

    // http://127.0.0.1:8080/index?num=0
    @RequestMapping("/index")
    public int MyIndexPage(int num) {
    
    

        int j = 1 / num;
        return j;
    }
}

2 异常处理

2.1 返回json

/*
 * @Author  : 有勇气的牛排(全网同名)
 * @FileName: CsExceptionHandler.java
 * desc     : 全局异常处理
 * */

package couragesteak.service;

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

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

@ControllerAdvice
public class CsExceptionHandler {
    
    
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody   // 响应json, 如果响应页面可以注释掉这个
    public Map<Object, Object> exceptionHandler() {
    
    
        HashMap<Object, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("msg", "系统错误");
        return result;
    }
}

image.png

猜你喜欢

转载自blog.csdn.net/zx77588023/article/details/130117073