spring自定义异常:
1.实现org.springframework.web.servlet.HandlerExceptionResolver
2.重写resolveException方法
3.配置此异常类的bean
4.在业务代码的适当位置抛出自定义异常
public class FileUploadException implements HandlerExceptionResolver {private static final Logger logger = LoggerFactory.getLogger(FileUploadException.class);
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// 处理各种异常逻辑
if(request != null){
if(request.getHeader("X-Requested-With") != null){
// 判断是否是ajax请求
if (request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1) {
if (ex instanceof DalException || ex instanceof SopSystemException) {
//获取引起该ex异常的异常
Throwable throwable = ex.getCause();
if (throwable instanceof SopSystemException
|| ex instanceof SopSystemException) {
logger.error("以上错误日志是执行" + request.getServletPath()
+ "操作时,上传文件失败~");
try {
if(request.getHeader("accept").indexOf("application/json") > -1){
//返回json格式
response.setContentType("application/json; charset=utf-8");
response.getWriter().write("{\"result\":\"ERROR\"}");} else{
response.getWriter().write("ERROR");
}
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
}
}
}
return null;
}
}