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})

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM