1.第一种方式是拦截所有跟控制层有关系的异常,通过继承一个父类controller,或者使用注解实现:
@RestControllerAdvice (统一返回json格式)
public class MyException{
@ExceptionHandler(Exception.class) (可以拦截具体的异常类)
public Object exception(Exception e) {
Map<String, Object> map = new HashMap();
map.put("msg", e.getMessage());
map.put("code", 204);
return map;
}
}
2.但是在其他地方产生的运行时异常,如果跟控制层没关系,我只能浅显的这么认为..如在filter发生的异常,则上面的方式拦截不到.如果用的是springboot框架,会自动返回一个json模板的异常信息.这时我们想自定义返回信息,就需要处理.
@Component
public class ErrorBaseeController extends DefaultErrorAttributes {
public static final String CUSTOM_ERROR_MAP_NAME = "customErrorMap";
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
Object message = map.get("message");
//设置传递自己定义的错误信息 (在要发生异常的地方set一下信息,这里就能取到了)
// Object attribute = webRequest.getAttribute(CUSTOM_ERROR_MAP_NAME, RequestAttributes.SCOPE_REQUEST);
Map mapp = new HashMap();
mapp.put("msg", message);
return mapp;
}
}
还有一种方式,因为springboot是统一将异常拦截到了/error路径下,所以我们可以重写他.,在可能发生问题的地方进行throw,然后将信息记录到request中;
@GetMapping("/error")
public Object error(HttpServletRequest request) {
String str = (String)request.getAttribute("自定义的异常信息");
return str ;
}