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方法的 ...
随机推荐
- ACM-ICPC 2018 南京赛区网络预赛 L. Magical Girl Haze 最短路+分层图
类似题解 There are NN cities in the country, and MM directional roads from uu to v(1\le u, v\le n)v(1≤u, ...
- BZOJ1632: [Usaco2007 Feb]Lilypad Pond SPFA+最短路计数
Description 为了让奶牛们娱乐和锻炼,农夫约翰建造了一个美丽的池塘.这个长方形的池子被分成了M行N列个方格(1≤M,N≤30).一些格子是坚固得令人惊讶的莲花,还有一些格子是岩石,其余的只是 ...
- UVa 12108 特别困的学生
https://vjudge.net/problem/UVA-12108 题意:给出n个学生的“清醒—睡眠”周期和初始时间点,每个学生在睡眠时需要判断全班睡觉人数是否严格大于清醒人数,否则在坚持一个清 ...
- UOJ #56. 【WC2014】非确定机
题意大意:给出一个输出文件,求输入. 1.满足所求的输入文件是一张图,n个点,m条边,所用算法是k(k在给出的输出文件中给出了) 2.算法是图论算法?!k基本上→两位数组成,若十位数相同,说明基本算法 ...
- python ros topic demo
发布者: #!/usr/bin/env python #coding=utf- import rospy from std_msgs.msg import String def talker(): ...
- python ros 使用launch文件启动脚本
目录结构 在包里面新建scripts文件夹,里面放运行的脚本文件,记得设置执行权限 然后新建launch文件夹,新建launch文件按照如下格式写: <node pkg="initia ...
- Spring boot 添加日志 和 生成接口文档
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring- ...
- CentOS下的Autoconf和AutoMake(完善篇) 3
在<实践篇>之后,由于需求不断修正,所以这篇是针对<实践篇>的一些完善.(以后内容会不定期增加完善) 1.不想链接到math的动态库,想连接到静态库①使用命令ldd ./mys ...
- spring boot 2.0+ 错误页面配置
如果访问了错误的路径,或者后台报错 如果没有一个统一的页面! 或者说页面上展示一堆报错信息,既影响美观,又对用户不友好! 那么如何配置? 定义 ErrorPageConfig,配置错误状态与对应访问路 ...
- 雷林鹏分享:C# 属性(Property)
C# 属性(Property) 属性(Property) 是类(class).结构(structure)和接口(interface)的命名(named)成员.类或结构中的成员变量或方法称为 域(Fie ...