企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ package com.nobb.controller.advice; import com.nobb.util.Response; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; //@ControllerAdvice + @ResponseBody @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BindException.class) public Object handleMethodArgumentNotValidException(BindException e) { BindingResult exceptions = e.getBindingResult(); if (exceptions.hasErrors()) { List<ObjectError> errors = exceptions.getAllErrors(); if (!errors.isEmpty()) { // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可 FieldError fieldError = (FieldError) errors.get(0); return Response.error(400, fieldError.getDefaultMessage()); } } return Response.error(400,"系统错误"); } } ~~~