异常的公共处理很多种,采用注解的方式,拦截器的方式等都可以,我采用的是继承 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. SPOJ - HIGH Highways(矩阵树定理)

    https://vjudge.net/problem/SPOJ-HIGH 题意: 给n个点m条边,求生成树个数. 思路: 矩阵树裸题. 具体的话可以看一下周冬的论文<生成树的计数及其应用> ...

  2. python 时间元组转时间戳

    #!/usr/bin/python # -*- coding: UTF- -*- import time print(time.mktime((, , , , , , , , ))) 输出 15382 ...

  3. 如何上传本地文件到github又如何删除自己的github仓库

    首先自己在https://github.com/网站要注册一个账户 自己上传工程到jithub,没有付费的用户只能选用public,意味着你的项目在全网是可以被看到和下载的: 所以涉及私密信息的,需要 ...

  4. 使用better-scroll遇到的问题

    项目中想给侧边栏添加一个滚动效果,用better-scroll帮助实现,引入better-scroll后,给外层最大盒子添加了<aside ref="asideMenu"&g ...

  5. 禁用表单元素 && 禁止选中

    一.禁用表单元素 1.dom设置属性 disabled="disabled" || disabled=true 2.css样式(高版本浏览器) pointer-events:non ...

  6. Codeforces 595B - Pasha and Phone

    595B - Pasha and Phone 代码: #include<bits/stdc++.h> using namespace std; #define ll long long # ...

  7. 区间数字的按位与 Bitwise AND of Numbers Range

    2018-08-13 22:50:51 问题描述: 问题求解: 首先如果m 和 n不相等,那么必然会有至少一对奇偶数,那么必然末尾是0. 之后需要将m 和 n将右移一位,直到m 和 n相等. 本质上, ...

  8. Spring源码的编译、下载和阅读

    原文出处: 分享牛 想对spring框架进行深入的学习一下,看看源代码,提升和沉淀下自己,工欲善其事必先利其器,还是先搭建环境吧. 环境搭建 sping源码之前是svn管理,现在已经迁移到了githu ...

  9. win7创建 VirtualBox COM 对象失败。 应用程序现在将终止。 Callee RC: E_NOINTERFACE (0x80004002)

    win7创建 VirtualBox COM 对象失败.  应用程序现在将终止.    Callee RC: E_NOINTERFACE (0x80004002) 启动VirtualBox提示这个错误, ...

  10. Greengenes Database(16S)

    The Greengenes Database Release 13_5 这是16S的一个非常重要的数据库 The Greengenes Database, a public resource sin ...