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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 {
/**
* 缺少参数
* @param e
* @return
*/
@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;
}
/**
* 请求过多
* @param e
* @return
*/
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
@ExceptionHandler({CurrentLimitException.class})
public AbstractResponse currentLimitException(CurrentLimitException e) {
AbstractResponse errorResponse = new SimpleResponse();
errorResponse.setErrorInfo(HttpStatus.TOO_MANY_REQUESTS.value(), e.getMessage());
return errorResponse;
}
}