2

一、springboot Restful使用@ControllerAdvice、@ExceptionHandler、@ResponseBody实现全局异常处理
@ControllerAdvice 注解定义全局异常处理类
@ExceptionHandler 指定自定义错误处理方法拦截的异常类型
同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器

1.定义异常业务类

/**
 * 异常VO
 * 
 * @date 2017年2月17日
 * @since 1.0.0
 */
public class ExceptionVO {

    private String errorCode;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }
}

2.定义自定义异常

package exception;

/**
 * 无数据Exception
 *
 * @date 17/4/25
 * @since 1.0.0
 */
public class NotFoundException extends SystemException {

    public NotFoundException(String message) {
        super(message);
    }
}


/**
 * 系统异常
 * 
 * @date 2017年2月12日
 * @since 1.0.0
 */
public class SystemException extends RuntimeException {

    private static final long serialVersionUID = 1095242212086237834L;

    protected Object errorCode;
    protected Object[] args;

    public SystemException() {
        super();
    }

    public SystemException(String message, Throwable cause) {
        super(message, cause);
    }

    public SystemException(String message) {
        super(message);
    }

    public SystemException(String message, Object[] args, Throwable cause) {
        super(message, cause);
        this.args = args;
    }

    public SystemException(String message, Object[] args) {
        super(message);
        this.args = args;
    }

    public SystemException(Object errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    public SystemException(Object errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public SystemException(Object errorCode, String message, Object[] args, Throwable cause) {
        super(message, cause);
        this.args = args;
        this.errorCode = errorCode;
    }

    public SystemException(Object errorCode, String message, Object[] args) {
        super(message);
        this.args = args;
        this.errorCode = errorCode;
    }

    public SystemException(Throwable cause) {
        super(cause);
    }

    public Object[] getArgs() {
        return args;
    }

    public Object getErrorCode() {
        return errorCode;
    }
}

3.定义全局异常处理类

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import NotFoundException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
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.bind.annotation.ResponseStatus;
import ExceptionVO;


/**
 * WEB异常处理器
 * 
 * @date 2017年2月16日
 * @since 1.0.0
 */
@ControllerAdvice("web") //指定异常处理期拦截范围
public class WebExceptionHandler {

    static Logger LOG = LoggerFactory.getLogger(WebExceptionHandler.class);

    @Autowired
    private MessageSource messageSource;

    @ExceptionHandler(FieldException.class)
    @ResponseStatus(HttpStatus.CONFLICT) //指定http响应状态
    @ResponseBody

    /**
     * 未找到数据
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NotFoundException.class)//指定异常类型
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ExceptionVO handleNotFoundException(NotFoundException e) {
        ExceptionVO vo = new ExceptionVO();
        fillExceptionVO(e, vo);
        return vo;
    }


    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    @ResponseBody
    public ExceptionVO handleSystemException(SystemException e) {
        ExceptionVO vo = new ExceptionVO();
        fillExceptionVO(e, vo);
        return vo;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public void globalError(Exception e) {
        LOG.error(e.getMessage(), e);
    }

    /**
     * 填充异常响应消息
     * 
     * @param e
     * @param vo
     */
    private void fillExceptionVO(SystemException e, ExceptionVO vo) {
        if (e.getMessage() != null) {
            String message = e.getMessage();
            try {
                message = messageSource.getMessage(e.getMessage(), e.getArgs(), LocaleContextHolder.getLocale());
            } catch (NoSuchMessageException ex) {
                ; // ignore
            }
            vo.setMessage(message);
        }
        vo.setErrorCode(String.valueOf(e.getErrorCode()));
    }
}

二、springboot 返回 ModelAndView

package exception.handler;

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

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
@Commpent
public class OverallExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception ex) {
        ModelAndView mav = new ModelAndView();
        System.out.println(ex.getMessage());
        mav.addObject("errMsg", ex.getMessage());
        mav.setViewName("error");
        return mav;
    }

}

其它方式:

@ControllerAdvice
public class GlobalExceptionHandler {

      @ExceptionHandler(value = Exception.class)
      public ModelAndView resolveException(HttpServletRequest request, Exception ex) throws Exception {
        ModelAndView mav = new ModelAndView();
        System.out.println(ex.getMessage());
        mav.addObject("errMsg", ex.getMessage());
        mav.setViewName("error");
        return mav;
      }
}

houshiqun689
83 声望3 粉丝

棒棒的的码农