Springboot项目的全局异常处理类

在controller的同级目录exception下新建一个Java Class文件,命名为GlobalExceptionHandler,内容如下

package cn.smxy.stest2022101601.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> handlerException(Exception exp) {
        Map<String, Object> map = new HashMap<String, Object>();
        String errorStr = "error: " + exp.getStackTrace()[0].getClassName() + "." + exp.getStackTrace()[0].getMethodName() + "() line:" + exp.getStackTrace()[0].getLineNumber() + "\n" + exp.toString();
        System.out.println(errorStr);
        map.put("mapCode", 500);
        map.put("mapMessage", errorStr);
        map.put("mapObject", null);
        return map;
    }

}

 

posted @ 2022-10-19 19:54  淡淡的晓山横雾  阅读(35)  评论(0)    收藏  举报