异常的公共处理很多种,采用注解的方式,拦截器的方式等都可以,我采用的是继承 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 异常公共处理的更多相关文章

  1. Util应用程序框架公共操作类(五):异常公共操作类

    任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务上的错误进行简单支持. 对于刚刚接触.Net的新手,碰到错误的时候,一般喜欢通过返回bool值的方式指示是否执行成功. public boo ...

  2. 系统中异常公共处理模块 in spring boot

    最近在用spring boot 做微服务,所以对于异常信息的 [友好展示]有要求,我设计了两点: 一. 在业务逻辑代码中,异常的抛出 我做了限定,一般只会是三种: 1. OmcException // ...

  3. @ExceptionHandler异常统一处理

    之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑 try{ .......... }catch(Exception1 e){ ...

  4. @ControllerAdvice+@ExceptionHandler处理架构异常捕获

    1.注解引入 1) @ControllerAdvice - 控制器增强 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) ...

  5. Util应用程序框架公共操作类(四):验证公共操作类

    为了能够验证领域实体,需要一个验证公共操作类来提供支持.由于我将使用企业库(Enterprise Library)的验证组件来完成这项任务,所以本文也将演示对第三方框架的封装要点. .Net提供了一个 ...

  6. springmvc 通过异常增强返回给客户端统一格式

    在springmvc开发中,我们经常遇到这样的问题:逻辑正常执行时返回客户端指定格式的数据,比如json,但是遇NullPointerException空指针异常,NoSuchMethodExcept ...

  7. Util应用程序框架公共操作类

    随笔分类 - Util应用程序框架公共操作类 Util应用程序框架公共操作类 Util应用程序框架公共操作类(五):异常公共操作类 摘要: 任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务 ...

  8. 统一异常处理@ExceptionHandler

    异常处理功能中用到的注解是:@ExceptionHandler(异常类型.class). 这个注解的功能是:自动捕获controller层出现的指定类型异常,并对该异常进行相应的异常处理. 比如我要在 ...

  9. @ControllerAdvice注解(全局异常捕获)

    背景 @ControllerAdvice 注解 通常用于定义@ExceptionHandler, @InitBinder和@ModelAttribute 适用于所有@RequestMapping方法的 ...

随机推荐

  1. json获取元素数量

    var keleyijson={"plug1":"myslider","plug2":"zonemenu"} funct ...

  2. 【Ctsc2011】幸福路径

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2306 给定一张有向图,每个点有权值,蚂蚁从某个节点出发,初始体力值为$1$,每走一条边$体 ...

  3. AtCoder square869120 Contest #3 F sushi

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000 作者博客:http://www.cnblogs.com/ljh2000-jump/ ...

  4. Yandex.Algorithm 2011 Round 2 D. Powerful array 莫队

    题目链接:点击传送 D. Powerful array time limit per test 5 seconds memory limit per test 256 megabytes input ...

  5. python 正则表达式匹配特定浮点数

    def is_decimal(num): import re #以数字开头,小数点后保留1位数字或两位数字或者没有小数部分 dnumre = re.compile(r""" ...

  6. C++指针总结

    在C++中通过动态创建的对象,我们只能获得一个指针,并通过指针控制它.指针是存放对象的内存地址值,更准确的描述是对象的起始地址值.每一个指针都有一个相关的类型,不同数据类型的指针之间的区别不在指针的描 ...

  7. http和WebSocket

    有关http和WebSocket 的区别网上有很多的质料. 个人在此仅仅是记录以下自己的学习心得,自己的理解. 1. http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要 ...

  8. 检验二叉树序列化的合理性 Verify Preorder Serialization of a Binary Tree

    2018-07-31 17:47:13 问题描述: 问题求解: 本题要求在不构建二叉树的情况下对先序遍历生成的序列化字符串进行合法性验证,这里有个技巧性较强的验证方法,就是采用当前可用的指针数目进行验 ...

  9. [.NET开发] C#面向服务WebService从入门到精通

    C#面向服务WebService从入门到精通>包含以下两个部分: 一.<C#远程调用技术WebService修炼手册[基础篇]> 本次分享课您将学习到以下干货知识点: 1).WebS ...

  10. English trip -- VC(情景课) 8 A Get ready

    Words cashier  # 收银员                a cashier counts money   收钱 custodian  # 清洁工     a custodian  cl ...