一、使用@RestControllerAdvice
只能处理controller层返回报错,如果是dao层,则需要配合aop抛出异常,再捕获
@ControllerAdvice
public class MyExceptionHandler {
private Logger logger = LoggerFactory.getLogger("MyExceptionHandler");
@ResponseBody
@ExceptionHandler(Exception.class)
public Map<String, Object> errorHandler(Exception ex) {
Map<String, Object> map = new HashMap<>();
// 根据不同错误获取错误信息
if (ex instanceof IException) {
map.put("code", ((IException) ex).getCode());
map.put("msg", ex.getMessage());
} else if (ex instanceof TokenException) {
map.put("code", ((TokenException) ex).getCode());
map.put("msg", ex.getMessage());
} else {
String message = ex.getMessage();
map.put("code", 500);
map.put("msg", message == null || message.trim().isEmpty() ? "未知错误" : message);
// map.put("details", message);
logger.error(message, ex);
ex.printStackTrace();
}
return map;
}
}
二、使用切面@Aspect
@Aspect
@Slf4j
@Component
public class GlobalExceptionAspect
{
@Pointcut("execution(* com.jooan..*.*(..))")
public void pointcut()
{
}
@AfterThrowing(pointcut = "pointcut()",
throwing = "e")
public JsonResult afterThrowing(JoinPoint joinPoint, Throwable e) throws Exception
{
log.error("全局捕获到异常了..............",e);
//纪录错误信息
throw new Exception("服务器异常");
}
}
借鉴文章链接:https://blog.csdn.net/wowwilliam0/article/details/88978659