一、首先自定义一个异常拦截器
1、拦截异常所有 及拦截 Exception异常
package com.cg.demo.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 说明:
*
* @auther panhh
* @date 2019/7/12 9:37
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
//捕获所有异常 获取内部异常处理类:Exception
private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Map excption(Exception e, HttpServletRequest request){
String eMessage = e.getMessage();
StringBuffer url = request.getRequestURL();
System.out.println("ErrorMsg-->"+eMessage);
System.out.println("url-->"+url);
//打印日志
LOG.error("错误信息-->"+eMessage+"===请求链接--->"+url);
HashMap<Object, Object> hashMap = new HashMap<>();
hashMap.put("msg",eMessage);
hashMap.put("url",url);
return hashMap;
}
}
2、效果测试
@Controller
public class ExcTestController {
@RequestMapping("/test")
@ResponseBody
public String test(){
int a = 4/0;
return "test";
}
}
2、拦截器效果(控制台打印)
ErrorMsg-->/ by zero
url-->http://localhost:8080/test
2019-07-12 09:59:11.124 ERROR 10096 --- [nio-8080-exec-5] c.c.d.exception.GlobalExceptionHandler : 错误信息-->/ by zero===请求链接--->http://localhost:8080/test
3、页面返回内容:
{"msg":"/ by zero","url":"http://localhost:8080/test"}
二、自定义一个异常,自定义异常需要自己抛出
1、自定义一个异常
pac