首页>代码>基于spring boot2+mybatis+bootstrap开发的个人博客系统>/sbblog/src/main/java/com/lee/common/GlobalExceptionHandler.java
package com.lee.common;

import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * post请求参数校验抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Message methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        //获取异常中随机一个异常信息
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return Message.fail(defaultMessage);
    }

    /**
     * get请求参数校验抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Message bindExceptionHandler(BindException e){
        //获取异常中随机一个异常信息
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return Message.fail(defaultMessage);
    }

    /**
     * 请求方法中校验抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Message constraintViolationExceptionHandler(ConstraintViolationException e){
        //获取异常中第一个错误信息
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return Message.fail(message);
    }
}
最近下载更多
xk16675552250  LV33 1月11日
WHY-small  LV15 2023年12月13日
ysugxx  LV9 2023年12月5日
2410068425  LV23 2023年12月3日
luqi40281518  LV7 2023年10月7日
lvhongquan  LV11 2023年9月20日
186092  LV4 2023年9月19日
放opdf  LV6 2023年8月20日
微信网友_6199690640592896  LV1 2023年6月26日
1222222tcyy  LV8 2023年6月6日
最近浏览更多
denliv_hui  LV13 昨天
yellow_flowers  LV8 昨天
ssh123  LV10 4月23日
g815835618  LV2 4月12日
105789420  LV1 3月23日
chenlie  LV2 3月18日
yangyang567  LV1 3月8日
暂无贡献等级
邓子俊 2月27日
暂无贡献等级
bin2337  LV4 1月22日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友