springboot统一异常处理类及注解参数为数组的写法

统一异常处理类

package com.wdcloud.categoryserver.common.exception;

import com.wdcloud.categoryserver.common.constant.CodeConstants;
import com.wdcloud.categoryserver.common.entity.BaseView;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.RestController;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.servlet.http.HttpServletRequest;

/**
 * @describe: 全局异常处理
 * @author: zhuchunwang
 * @date: 2018/5/29 17:40
 * @version: 1.0
 */
@ControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {
    /**
     * 默认未知异常
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        return  new BaseView(CodeConstants.SYSTEM_EXCEPTION,CodeConstants.SYSTEM_EXCEPTION_MSG);
    }

    /**
     * 参数异常
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {HttpMessageNotReadableException.class, MissingServletRequestPartException.class})
    @ResponseBody
    public BaseView httpMessageNotReadableExceptionErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        return  new BaseView(CodeConstants.PARAMETER_ERROR,CodeConstants.PARAMETER_ERROR_MSG);
    }
}

一个参数时这样写

@ExceptionHandler(value = HttpMessageNotReadableException.class)

多个参数时这样写

@ExceptionHandler(value = {HttpMessageNotReadableException.class, MissingServletRequestPartException.class})
原文地址:https://www.cnblogs.com/zhucww/p/9167857.html