Java,SpringBoot,Validation验证框架,统一返回错误信息

  • A+
所属分类:体育平台

Java,SpringBoot,Validation验证框架,统一返回错误信息

前言

SpringBoot项目,Validation验证框架,接着上一篇,每个Controller方法都进行一次处理,比较累,因此,在这里做统一返回。

代码

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

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class AllExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(Exception e) {
        // 验证错误,统一返回
        if (e instanceof org.springframework.web.bind.MethodArgumentNotValidException) {
            MethodArgumentNotValidException ee = (MethodArgumentNotValidException) e;
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", "valid");
            resultMap.put("message", ee.getMessage());
            return resultMap;
        } else if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            //404 Not Found
            return e;
        } else {
            //500
            return e;
        }
    }

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: