异常的公共处理很多种,采用注解的方式,拦截器的方式等都可以,我采用的是继承 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. 【第七章】 springboot + retrofit

    retrofit:一套RESTful架构的Android(Java)客户端实现. 好处: 基于注解 提供JSON to POJO,POJO to JSON,网络请求(POST,GET,PUT,DELE ...

  2. Java中线程出现Exception in thread "Thread-0" java.lang.IllegalMonitorStateException异常 解决方法

    代码 package thread; public class TestChongNeng { public static void main(String[] args) { Thread t1 = ...

  3. [BZOJ3613][Heoi2014]南园满地堆轻絮 二分答案

    Description 小 Z 是 ZRP(Zombies’ Republic of Poetry,僵尸诗歌共和国)的一名诗歌爱好者,最近 他研究起了诗词音律的问题.   在过去,诗词是需要编成曲子唱 ...

  4. 《EMCAScript6入门》读书笔记——23.Module的加载实现

  5. Jmeter 同一个测试计划下的多个线程组 执行顺序 希望调整为顺序执行

    用Jmeter做自动化测试,一个测试计划中添加多个线程组, 每个线程组的功能测试,希望是一个线程组执行完毕后,接着执行下一个线程组下的请求 Jmeter默认多个线程组之间是并行关系 需要在测试计划下勾 ...

  6. a 样式重置 常见用法

    样式重置 a:link, a:visited, a:hover, a:active{   color: #fff;   text-decoration: none; }   常见用法  ( rel=& ...

  7. C++指针总结

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

  8. 解决RDP连接不上

    1,开始->运行 regedit 删除注册表项目:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft, 删除MSLicensing.2,开始--运行 mstsc /v:( ...

  9. English trip -- VC(情景课)10 B Around the house 在家里

    Vocablulary focus  核心词汇 cook play the guitar listen to music watch TV read magazines work in the gar ...

  10. android--------面试题收集

    Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发.这里会不断收集和更新Android基础相关的面试题 ...