Spring全局异常捕获

package org.xxx.ac.zpk.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.wpwl.ac.utils.JSONUtils;
import org.wpwl.ac.zpk.entity.ApiResult;
/**
 * 异常处理
 * @author xxx
 *
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        ModelAndView mv = new ModelAndView();
        /* 使用response返回 */
        response.setStatus(HttpStatus.OK.value()); // 设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
        response.setCharacterEncoding("UTF-8"); // 避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            ApiResult json = getExceptionResult(ex);
            response.getWriter().write(JSONUtils.bean2Json(json));
        } catch (IOException e) {
            logger.error("与客户端通讯异常:" + e.getMessage(), e);
        }

        logger.debug("异常:" + ex.getMessage(), ex);
        return mv;
    }

    private ApiResult getExceptionResult(Exception ex) {
        ApiResult result;
        if (ex instanceof WPException) {
            result = ApiResult.err(ex.getMessage());
        } else {
            result = ApiResult.err("服务异常!");
        }
        return result;
    }

}
<bean id="exceptionResolver" class="org.wpwl.ac.zpk.exception.ExceptionHandler"/> 
package org.wpwl.ac.zpk.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wpwl.ac.zpk.entity.ApiResult;

public class ExceptionController {

//    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @ExceptionHandler
    @ResponseBody
    public ApiResult exception(HttpServletRequest request, Exception e) {
        //添加自己的异常处理逻辑,如日志记录   
        request.setAttribute("exceptionMessage", e.getMessage());
//        e.printStackTrace();
//        logger.error(e.getMessage());
        // 根据不同的异常类型进行不同处理
        if(e instanceof WPException){
            return ApiResult.err(e.getMessage());
        }
        else{
            return ApiResult.err("服务异常!");
        }
    }
}
时间: 2024-08-10 23:30:20

Spring全局异常捕获的相关文章

spring boot2.0+中添加全局异常捕获

1.添加自定义异常,继承RuntimeException,为什么继承RuntimeException呢?是因为我们的事务在RuntimeException异常下会发生回滚. 1 public class BusinessException extends RuntimeException{ 2 3 public BusinessException(String code, String msg){ 4 this.code = code; 5 this.msg = msg; 6 } 7 8 pri

Spring-MVC开发之全局异常捕获全面解读(转)

异常,异常.我们一定要捕获一切该死的异常,宁可错杀一千也不能放过一个!产品上线后的异常更要命,一定要屏蔽错误内容,以免暴露敏感信息!在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种: WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉,互相没

自定义全局异常捕获

原文:http://blog.csdn.net/jinzhencs/article/details/51700009 第一种:实现HandlerExceptionResolver 注意: 把错误码 重设成200,不然还是返回的异常信息. 注解@Compoment交由spring创建bean 之后就能愉快的返回自己的错误码了. 或者记录错误日志. /** * 全局异常捕获 * @author Mingchenchen * */ @Component public class GlobleExcep

Spring-MVC开发之全局异常捕获全面解读

在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种, WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉 互相没有依赖,每个都可单独使用! 定义服务器错误WEB.XML整合Spring MVC web.xml <error-page> <

MVC 好记星不如烂笔头之 ---&gt; 全局异常捕获以及ACTION捕获

public class BaseController : Controller { /// <summary> /// Called after the action method is invoked. /// </summary> /// <param name="filterContext">Information about the current request and action.</param> protected ov

C#中的那些全局异常捕获

1.WPF全局捕获异常 public partial class App : Application { public App() { // 在异常由应用程序引发但未进行处理时发生.主要指的是UI线程. this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); //  当某

Configure、中间件与ErrorHandlingMiddleware全局异常捕获

一.Configure Startup.cs中的Configure方法主要是http处理管道配置.中间件和一些系统配置,其中 IApplicationBuilder: 定义一个类,该类提供配置应用程序请求的机制管道.通过IApplicationBuilder下的run.use方法传入管道处理方法.这是最常用方法,对于一个真实环境的应用基本上都需要比如权限验证.跨域.异常处理等. IHostingEnvironment:提供有关正在运行的应用程序的web托管环境的信息 简单来说Configure方

springboot编程之全局异常捕获

springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息 package com.imooc.web.controller; import com.imooc.exception.UserNotExistException; import org.spr

Spring 框架——利用HandlerExceptionResolver实现全局异常捕获

https://blog.csdn.net/qq_22172133/article/details/82147630 微信一.需求描述        因为在项目中,我们不可否认的会出现异常,而且这些异常并没有进行捕获.经常出现的bug如空指针异常等等.在之前的项目中,如果我们没有进行任何配置,那么容器会自动打印错误的信息,如果tomcat的404页面,400页面等等.如果我们在web.xml中进行如下配置,就会拦截错误,然后跳转到指定的错误页面. <error-page>    <err