首页>代码>基于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);
    }
}
最近下载更多
zolscy  LV24 2024年12月18日
xk16675552250  LV33 2024年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日
最近浏览更多
dane168  LV8 2月17日
nightstarshii 1月26日
暂无贡献等级
三秋桂子  LV1 2024年12月22日
ma406805131  LV19 2024年12月18日
dengge123  LV14 2024年12月13日
zolscy  LV24 2024年12月9日
tiancj  LV1 2024年11月25日
krispeng  LV14 2024年11月20日
微信网友_6797029372219392  LV2 2024年10月29日
栾庆浩 2024年10月23日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友