在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