实现 HandlerExceptionResolver ,对自定义异常进行转换,对非自定义异常统一转化为自定义异常并打印日志
public class BizBusinessExceptionHandler implements HandlerExceptionResolver {
private static final Logger logger = LogManager.LOGGER.getInstance();
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object o, Exception e) {
BusinessException exception;
ErrorRes errorRes;
if (e instanceof BusinessException) {
exception = (BusinessException) e;
errorRes = ErrorRes.builder().errCode(exception.getErrorCode())
.errMsg(exception.getMessage()).build();
} else {
logger.error("unexpected exception!",e);
exception = new BusinessException(ErrorCode.SYSTEM_ERROR);
errorRes = ErrorRes.builder().errCode(exception.getErrorCode())
.errMsg(exception.getMessage()).build();
}
PrintWriter responseWriter = null;
try {
response.setContentType("application/json;");
response.setCharacterEncoding("UTF-8");
response.setStatus(Response.SC_OK);
responseWriter = response.getWriter();
responseWriter.write(JSON.toJSONString(errorRes));
responseWriter.flush();
} catch (IOException e1) {
} finally {
if (responseWriter != null) {
responseWriter.close();
}
}
return new ModelAndView();
}
}
网友评论