ExceptionAdvice.java 1.24 KB
Newer Older
xieshaojun's avatar
xieshaojun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
package vc.thinker.exception;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vc.thinker.response.AbstractResponse;
import vc.thinker.response.SimpleResponse;

import java.util.List;

/**
 * @author : xieshaojun
 * @date : 2023/1/3 15:21
 */
@RestControllerAdvice(annotations = RestController.class)
public class ExceptionAdvice {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public AbstractResponse handleBodyValidException(MethodArgumentNotValidException e) {
        AbstractResponse errorResponse = new SimpleResponse();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        errorResponse.setErrorInfo(HttpStatus.BAD_REQUEST.value(), fieldErrors.get(0).getDefaultMessage());
        return errorResponse;
    }
}