springmvc统一异常管理

springmvc统一异常管理

首先贴出来xml配置和代码

<context:component-scan base-package="com.szq.learn.exceptionhandler" />

上面配置配置spring扫描项

package com.szq.learn.exceptionhandler;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.szq.learn.constants.LearnResultConstants;

@ControllerAdvice
public class UnifiedExceptionhandler extends ResponseEntityExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

    @ResponseBody
    @ExceptionHandler(Exception.class)
    protected Map<String, Object> handleNoneStandardSpringMVCExceptions(Exception ex, WebRequest request) {
        logger.warn("", ex);
        return LearnResultConstants.fail;
    };
}

上面代码是实际异常处理代码
可以看出该类继承了ResponseEntityExceptionHandler类,打开ResponseEntityExceptionHandler类源码,可以看到

/**
     * Provides handling for standard Spring MVC exceptions.
     * @param ex the target exception
     * @param request the current request
     */
    @SuppressWarnings("deprecation")
    @ExceptionHandler({
            org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            MethodArgumentNotValidException.class,
            MissingServletRequestPartException.class,
            BindException.class,
            NoHandlerFoundException.class,
            AsyncRequestTimeoutException.class
        })
    public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
    ... ...
    }

说明该类已经提供了方法处理springcontroller类可能抛出的标准异常,继承该类后再自己定义一个方法,标注@ExceptionHandler注解来处理controller可能抛出的其他异常就可实现异常的统一处理。


原创不易,转帖请注明出处 — shizhongqi


猜你喜欢

转载自blog.csdn.net/lianjunzongsiling/article/details/77951395