ExceptionHandler 异常公共处理
异常的公共处理很多种,采用注解的方式,拦截器的方式等都可以,我采用的是继承 AbstractHandlerExceptionResolver 来实现,
上代码
package com.yun.util; import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; import com.alibaba.druid.support.json.JSONUtils; public class ExceptionHandler extends AbstractHandlerExceptionResolver { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class); @Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { // SQLException 数据库异常
if (ex instanceof SQLException) {
SQLException e = (SQLException) ex;
LOGGER.error("数据库异常:{}",e.getMessage());
}
// RuntimeException>NullPointerException,IllegalArgumentException...
if (ex instanceof RuntimeException) {
RuntimeException e = (RuntimeException) ex;
LOGGER.error("运行时异常:{}",e.getMessage());
} // IOException
if (ex instanceof IOException) {
IOException e = (IOException) ex;
LOGGER.error("IO异常:{}",e.getMessage());
} // TimeoutException
if (ex instanceof TimeoutException) {
TimeoutException e = (TimeoutException) ex;
LOGGER.error("超时:{}",e.getMessage());
} if(handler instanceof HandlerMethod){ HandlerMethod handlerMethod = (HandlerMethod) handler;
Class returnType = handlerMethod.getMethod().getReturnType();
try {
if(returnType == String.class||returnType==void.class){
String rsp = JSONUtils.toJSONString(ex);
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(rsp);
new ModelAndView();
}
if(returnType == ModelAndView.class){
Map<String, Object> model = new HashMap<String, Object>();
model.put("ex", ex);
return new ModelAndView("error/error", model);
}
} catch (Exception e) {
LOGGER.error("异常:{}", e.getMessage());
} } return new ModelAndView(); } }
接下来只需要注册到spring中就ok了。
<!-- 异常处理 -->
<bean class="com.midea.jr.efc.eac.core.web.ExceptionHandler"></bean>
二: 另一种方式 注解 ControllerAdvice
package com.yun.util; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
public class CommonExceptiomHandler { private Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public String illegalArgumentException(IllegalArgumentException e) {
logger.error(e.getMessage());
return new String("param error");
} @ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseBody
public String MissingServletRequestParameterException(MissingServletRequestParameterException e) {
logger.error(e.getMessage());
return new String("missing servlet request");
} @ExceptionHandler(TypeMismatchException.class)
@ResponseBody
public String typeMismatchException(TypeMismatchException e) {
logger.error(e.getMessage());
return new String("type mismatch error");
} @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
public String httpRequestMethodNotSupportedException(Exception e) {
logger.error(e.getMessage());
return new String("http request method not supported");
} @ExceptionHandler(Exception.class)
@ResponseBody
public String defaultException(Exception e) {
logger.error(e.getMessage());
return new String("system error");
} }
ExceptionHandler 异常公共处理的更多相关文章
- Util应用程序框架公共操作类(五):异常公共操作类
任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务上的错误进行简单支持. 对于刚刚接触.Net的新手,碰到错误的时候,一般喜欢通过返回bool值的方式指示是否执行成功. public boo ...
- 系统中异常公共处理模块 in spring boot
最近在用spring boot 做微服务,所以对于异常信息的 [友好展示]有要求,我设计了两点: 一. 在业务逻辑代码中,异常的抛出 我做了限定,一般只会是三种: 1. OmcException // ...
- @ExceptionHandler异常统一处理
之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑 try{ .......... }catch(Exception1 e){ ...
- @ControllerAdvice+@ExceptionHandler处理架构异常捕获
1.注解引入 1) @ControllerAdvice - 控制器增强 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) ...
- Util应用程序框架公共操作类(四):验证公共操作类
为了能够验证领域实体,需要一个验证公共操作类来提供支持.由于我将使用企业库(Enterprise Library)的验证组件来完成这项任务,所以本文也将演示对第三方框架的封装要点. .Net提供了一个 ...
- springmvc 通过异常增强返回给客户端统一格式
在springmvc开发中,我们经常遇到这样的问题:逻辑正常执行时返回客户端指定格式的数据,比如json,但是遇NullPointerException空指针异常,NoSuchMethodExcept ...
- Util应用程序框架公共操作类
随笔分类 - Util应用程序框架公共操作类 Util应用程序框架公共操作类 Util应用程序框架公共操作类(五):异常公共操作类 摘要: 任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务 ...
- 统一异常处理@ExceptionHandler
异常处理功能中用到的注解是:@ExceptionHandler(异常类型.class). 这个注解的功能是:自动捕获controller层出现的指定类型异常,并对该异常进行相应的异常处理. 比如我要在 ...
- @ControllerAdvice注解(全局异常捕获)
背景 @ControllerAdvice 注解 通常用于定义@ExceptionHandler, @InitBinder和@ModelAttribute 适用于所有@RequestMapping方法的 ...
随机推荐
- 《EMCAScript6入门》读书笔记——16.Generator函数的语法
鼠标指针移到图片上,右键,选择在“在新标签页中打开”,放大即可看到清晰文字.
- 操作构造字符串化宏#define STRINGIZE(x) #x
c++test工程单元测试中报错 “STRINGIZE” 未定义错误 解决方案:在头文件定义宏STRINGIZE #符号把一个符号直接转换为字符串,例如:#define STRINGIZE(x) #x ...
- BZOJ 1005: [HNOI2008]明明的烦恼(prufer数列)
http://www.lydsy.com/JudgeOnline/problem.php?id=1005 题意: Description 自从明明学了树的结构,就对奇怪的树产生了兴趣......给出标 ...
- POJ 1222 EXTENDED LIGHTS OUT(高斯消元解XOR方程组)
http://poj.org/problem?id=1222 题意:现在有5*6的开关,1表示亮,0表示灭,按下一个开关后,它上下左右的灯泡会改变亮灭状态,要怎么按使得灯泡全部处于灭状态,输出方案,1 ...
- Linux 常用的压缩命令有 gzip 和 zip
Linux 常用的压缩命令有 gzip 和 zip,两种压缩包的结尾不同:zip 压缩的后文件是 *.zip ,而 gzip 压缩后的文件 *.gz 相应的解压缩命令则是 gunzip 和 unzip ...
- Windows10中注册 regsvr32 xxx.ocx报错but the call to DIIRegisterServer failed with error code 0x80040200
网站中有读取居民身份证的机器,需要安装一些注册activeX控件然后进入指定目录下执行以下命令regsvr32 xxx.ocx报了个错: but the call to DIIRegisterServ ...
- string 和 wstring
区别: char* wchar_t 一个字节 两个字节 ACSII编码 unicode编码 转换: 1.Windows API WideCharToMultiByte() MultiByteToWid ...
- English trip -- MC(情景课)6 Time
xu言: 学习就和打仗一样,在开始前一定先要有准备(预习).这样在真正开始打的时候你会发现,本以为很难的仗,你却越战越勇,逐渐进入状态. Vocabulary focus gym [dʒɪm] ...
- Angular2 -- 生命周期
组件生命周期钩子 指令和组件的实例有一个生命周期:新建.更新和销毁. 每个接口都有唯一的一个钩子方法,它们的名字是由接口名加上 ng前缀构成的.比如,OnInit接口的钩子方法叫做ngOnInit. ...
- hdu-2227-dp+bit
Find the nondecreasing subsequences Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/3 ...