工程中我们不可否认的会出现异常,而且这些异常并没有进行捕获。经常出现的bug如空指针异常等等。在之前的项目中,如果我们没有进行任何配置,那么容器会自动打印错误的信息,如果tomcat的404页面,400页面等等。如果我们在web.xml中进行如下配置,就会拦截错误,然后跳转到指定的错误页面。
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
但是这已经落后了,现在我们通过实现spring的HandlerExceptionResolver接口来捕获所有的异常。 主要作用是,比如当我们在Web API 提供服务的时候,API自己故障了,那么在API 故障前我们可以再设定一个springboot框架自身的 异常检测。
demo如下:
package com.demo.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.credithc.kg.fetures.model.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
private ModelAndView modelAndView = new ModelAndView();
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
try {
log.error("系统运行时异常:{}",e);
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().print(JSONObject.toJSON(ResultDTO.fail("系统异常")));
} catch (IOException e1) {
log.error("响应IO异常:{}",e1);
}
return modelAndView;
}
}
import lombok.Data;
@Data
public class ResultDTO<T> {
private Integer code;
private String msg;
private T body;
private ResultDTO(Integer code, String msg, T body) {
this.code = code;
this.msg = msg;
this.body = body;
}
public static <T> ResultDTO success(T body){
return success(200,"成功",body);
}
public static ResultDTO success(Integer code, String msg){
return success(code,msg,null);
}
public static ResultDTO fail(String msg){
return success(500,msg);
}
public static <T> ResultDTO success(Integer code, String msg, T body){
return new ResultDTO(code,msg,body);
}
}
参考: