package com.bear.mobile.util;
import com.bear.mobile.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(BindException.class)
public ResponseDatahandlerBindException(BindException exception) {
return handlerNotValidException(exception);
? ? }
/**
? ? * 對(duì)方法參數(shù)校驗(yàn)異常處理方法(前端提交的方式為json格式出現(xiàn)異常時(shí)會(huì)被該異常類處理)
? ? * json格式提交時(shí)堂竟,spring會(huì)采用json數(shù)據(jù)的數(shù)據(jù)轉(zhuǎn)換器進(jìn)行處理(進(jìn)行參數(shù)校驗(yàn)時(shí)錯(cuò)誤是拋出MethodArgumentNotValidException異常)
? ? */
? ? @ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseDatahandlerArgumentNotValidException(MethodArgumentNotValidException exception) {
return handlerNotValidException(exception);
? ? }
public ResponseDatahandlerNotValidException(Exception e) {
log.debug("begin resolve argument exception");
? ? ? ? BindingResult result;
? ? ? ? if (einstanceof BindException) {
BindException exception = (BindException) e;
? ? ? ? ? ? result = exception.getBindingResult();
? ? ? ? }else {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
? ? ? ? ? ? result = exception.getBindingResult();
? ? ? ? }
StringBuilder stringBuilder =new StringBuilder();
? ? ? ? if (result.hasErrors()) {
List fieldErrors = result.getFieldErrors();
? ? ? ? ? ? fieldErrors.forEach(error -> {
//? ? ? ? ? ? ? ? stringBuilder.append(error.getField()+":");
? ? ? ? ? ? ? ? stringBuilder.append(error.getDefaultMessage()+" ");
? ? ? ? ? ? });
? ? ? ? }
log.error("傳遞參數(shù)異常:"+stringBuilder.toString());
? ? ? ? return ResponseData.error(stringBuilder.toString());
? ? }
}