springMVC global exception


How to use HandlerExceptionResolver for global exception handling in Spring

  1. Configure log4jjar package
    write picture description here

  2. Implement the HandlerExceptionResolver interface

package cn.e3mall.search.exception;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
 * springMVC的全局错误
 * @author yuhf
 *
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    //日志输出
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class); 

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
            Exception exception) {
        //打印控制台
        exception.printStackTrace();
        //写日志
        logger.debug("测试输出的日志。。。。。。。");
        logger.info("系统发生异常了。。。。。。。");
        logger.error("系统发生异常", exception);
        //发邮件、发短信
        //使用jmail工具包。发短信使用第三方的Webservice。
        //显示错误页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/exception");
        return modelAndView;
    }

}
  1. Configure in springMVC
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:conf/resource.properties" />
    <!-- 扫描包,所有的controller cn.e3mall.portal.controller.IndexController-->
    <context:component-scan base-package="cn.e3mall.search.controller" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 资源映射 -->
    <!-- 只要是访问/css/** 都被映射到根目录的/css/下面 
    <mvc:resources location="/css/" mapping="css/**"></mvc:resources>
    <mvc:resources location="/js/" mapping="js/**"></mvc:resources>
     -->
    <!-- 使用dubbo发布服务 -->
    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="e3-search-web" />
    <!--  192.168.31.135  192.168.1.108-->
    <dubbo:registry protocol="zookeeper" address="192.168.31.40:2181" />

        <!-- 全局异常处理器 -->
    <bean class="cn.e3mall.search.exception.GlobalExceptionResolver"/>

    <!-- 声明需要暴露的服务接口-->
    <dubbo:reference interface="cn.e3mall.search.service.SearchService" id="searchService"/>
</beans>
  1. Add log4j configuration file
    write picture description here
    configuration content
#日志的权限
log4j.rootLogger=INFO,A3,STDOUT

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=[%p] [%l] %10.10c - %m%n

log4j.appender.A3=org.apache.log4j.RollingFileAppender
#日志地址
log4j.appender.A3.file=logs/server.log
log4j.appender.A3.MaxFileSize=1024KB
log4j.appender.A3.MaxBackupIndex=10
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=\n\n[%-5p] %d{yyyy-MM-dd HH\:mm\:ss,SSS} method\:%l%n%m%n

Related


Python global exception handling

Kye Russell: I want to catch up KeyboardInterruptglobally and cope well. I don't want to wrap my entire script in one giant try/except statement. What is the solution? Various interfaces: sys.excepthookYou can change it if you really don't want to use it try/e

Java: Global exception handler

Martijn Courteaux: Is there a way to create a global exception handler in Java. I want to use like this: "When an exception is thrown somewhere in the WHOLE program, exit." The handler may fail to catch exceptions thrown in the try-catchbody . Martin bobbymcr

Global exception handler in Java

Samuh: I'm thinking of using Thread.setDefaultUncaughtExceptionHandler(...)call to set a global default Exception handler for my (Android) mobile app (using Java syntax) . I'm thinking of just showing the user an alert dialog with the appropriate message. Are

global exception handling

Lance Hardwood: Is it possible to globally catch exceptions thrown in an Angular 2 application to prevent the whole application from breaking due to a bug in any one component? Saulfa : As Google explains, you can override the error handler service to do what

WPF global exception handler

Scott Olson Sometimes, in non-reproducible situations, my WPF application crashes without any message. The app just closes immediately. Where is the best place to implement a global Try/Catch block. At least I had to implement a message box with the message: "

WebAPI global exception handling

tis I have an ASP WebAPI project. I am trying to set a global exception handler on my basecontroller. So I created one ExceptionFilterAttributelike this. using System.Web.Http.Filters; public class MyExceptionFilterAttribute : ExceptionFilterAttribute { p

Global exception handling in MVVM

Lucas Is there a way to implement global exception handling using the MVVM pattern. In my existing situation, as soon as an error occurs inside the ViewModel, the app doesn't crash, but just "hides" the rest of the bindings that happen after the code that caus

Python global exception handling

Kye Russell: I want to catch up KeyboardInterruptglobally and cope well. I don't want to wrap my entire script in one giant try/except statement. What is the solution? Various interfaces: sys.excepthookYou can change it if you really don't want to use it try/e

Global exception handling in Jersey

Trisfall: Is there a way to do global exception handling in Jersey? I wish there was a way to put this where the resource is actually called, rather than having a single resource with a try/catch block and then calling some method to clear any exceptions to be

Java: Global exception handler

Martijn Courteaux: Is there a way to create a global exception handler in Java. I want to use like this: "When an exception is thrown somewhere in the WHOLE program, exit." The handler may fail to catch exceptions thrown in the try-catchbody . Martin bobbymcr

Global exception handler in Java

Samuh: I'm thinking of using Thread.setDefaultUncaughtExceptionHandler(...)call to set a global default Exception handler for my (Android) mobile app (using Java syntax) . I'm thinking of just showing the user an alert dialog with the appropriate message. Are

Global exception handler in angularjs

Anand Gargate In angularjs, is it possible to add a global exception handler in one place? So even if you miss the opportunity to add an exception handler for any code user, you'll get a proper message. For example, something went wrong. salisbury angular.modu

Global Exception Handler WPF

Darren Rockett I'm trying to implement a global exception handler and the problem occurs when the following line generates an error that only stops in the debugger. var list = await _repository.GetAllAsync<ContactView>(); Application.Current.DispatcherUnha

WPF global exception handler

Scott Olson Sometimes, in non-reproducible situations, my WPF application crashes without any message. The app just closes immediately. Where is the best place to implement a global Try/Catch block. At least I had to implement a message box with the message: "

WebAPI global exception handling

tis I have an ASP WebAPI project. I am trying to set a global exception handler on my basecontroller. So I created one ExceptionFilterAttributelike this. using System.Web.Http.Filters; public class MyExceptionFilterAttribute : ExceptionFilterAttribute { p

Global exception handling in MVVM

Lucas Is there a way to implement global exception handling using the MVVM pattern. In my existing situation, as soon as an error occurs inside the ViewModel, the app doesn't crash, but just "hides" the rest of the bindings that happen after the code that caus

Global exception handling in MVVM

Lucas Is there a way to implement global exception handling using the MVVM pattern. In my existing situation, as soon as an error occurs inside the ViewModel, the app doesn't crash, but just "hides" the rest of the bindings that happen after the code that caus

global exception handling

Lance Hardwood: Is it possible to globally catch exceptions thrown in an Angular 2 application to prevent the whole application from breaking due to a bug in any one component? Saulfa : As Google explains, you can override the error handler service to do what

Flask global exception handling

serious How does Flask handle exceptions globally? I found a way to handle custom database interaction using: try: sess.add(cat2) sess.commit() except sqlalchemy.exc.IntegrityError, exc: reason = exc.message if reason.endswith('is not unique'):

global exception handling

Lance Hardwood Is it possible to globally catch exceptions thrown in an Angular 2 application to prevent the whole application from breaking due to a bug in any one component? sulfur As Google explains, you can override the error handler service to do what you

TAP global exception handler

Sam This code throws an exception. Is it possible to define an application global handler that will catch it? string x = await DoSomethingAsync(); Using .net 4.5 / WPF stuffy nose This is actually a good question if I understand correctly . I originally voted

MVC global exception

username I'm writing an MVC 5 internet application and have a problem with handling global exceptions. Application_ErrorI have the installer global.asaxin my file . This caters to bugs such as 404 HttpExceptions. How can I send all errors that happen in the co

Flask global exception handling

serious How does Flask handle exceptions globally? I found a way to handle custom database interaction using: try: sess.add(cat2) sess.commit() except sqlalchemy.exc.IntegrityError, exc: reason = exc.message if reason.endswith('is not unique'):

Python global exception handling

Kye Russell: I want to catch up KeyboardInterruptglobally and cope well. I don't want to wrap my entire script in one giant try/except statement. What is the solution? Various interfaces: sys.excepthookYou can change it if you really don't want to use it try/e

Global exception handling in Jersey

Trisfall: Is there a way to do global exception handling in Jersey? I wish there was a way to put this where the resource is actually called, rather than having a single resource with a try/catch block and then calling some method to clear any exceptions to be

Java: Global exception handler

Martijn Courteaux: Is there a way to create a global exception handler in Java. I want to use like this: "When an exception is thrown somewhere in the WHOLE program, exit." The handler may fail to catch exceptions thrown in the try-catchbody . Martin bobbymcr

Global exception handler in Java

Samuh: I'm thinking of using Thread.setDefaultUncaughtExceptionHandler(...)call to set a global default Exception handler for my (Android) mobile app (using Java syntax) . I'm thinking of just showing the user an alert dialog with the appropriate message. Are

Global Exception Handler WPF

Darren Rockett I'm trying to implement a global exception handler and the problem occurs when the following line generates an error that only stops in the debugger. var list = await _repository.GetAllAsync<ContactView>(); Application.Current.DispatcherUnha

WPF global exception handler

Scott Olson Sometimes, in non-reproducible situations, my WPF application crashes without any message. The app just closes immediately. Where is the best place to implement a global Try/Catch block. At least I had to implement a message box with the message: "