青羊经侦大队-数据平台
安瑾然
2022-07-11 57a7ec6424a287d8d857d99b1488b3b2ce74ff6c
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
package com.example.jz.config;
 
import com.example.jz.enums.BusinessHttpStatus;
import com.example.jz.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
/**
 * 自定义错误处理器
 */
@Controller
@RestControllerAdvice
public class DefaultExceptionHandlerConfig {
 
 
    @ExceptionHandler(BindException.class)
    public ResponseEntity<String> bindExceptionHandler(BindException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
 
    }
 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }
 
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> unauthorizedExceptionHandler(BusinessException e) {
        e.printStackTrace();
        return ResponseEntity.status(e.getHttpStatusCode()).body(e.getMessage());
    }
}