首页 > 其他分享 >Springboot项目的全局异常处理类

Springboot项目的全局异常处理类

时间:2022-10-19 20:03:18浏览次数:52  
标签:map Springboot getStackTrace errorStr exp put import 全局 异常

在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;
    }

}

 

标签:map,Springboot,getStackTrace,errorStr,exp,put,import,全局,异常
From: https://www.cnblogs.com/hghdbk/p/16807554.html

相关文章