【问题标题】:How to give specific error instead of 500 internal如何给出特定错误而不是 500 内部
【发布时间】:2021-10-08 18:28:18
【问题描述】:

我已经写了特定的异常,但我的 GlobalExceptionHandler 不起作用,任何帮助将不胜感激。谢谢。

下面是我的 GlobalException 类;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String EXCEPTION_OCCURED_LOG_PREFIX = "Exception occured: {}";
    public static final String EXCEPTION_OCCURED_LOG_DETAIL = "Exception log detail occured: {}, class: {}";
    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler({BadRequestException.class})
    public ResponseEntity<BaseResponse> handleBadRequest(BadRequestException ex) {


        String logSuffix = Arrays.toString(ex.getStackTrace());
        logger.error(EXCEPTION_OCCURED_LOG_PREFIX, logSuffix);
        logger.error(EXCEPTION_OCCURED_LOG_DETAIL, ex.getMessage(), ex.getClass());

        BaseResponse response = new BaseResponse();
        response.setCode(Constants.B_BADREQUEST);
        response.setMessage("BadRequestException occured! Exception details: ".concat(ex.getMessage()));

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(response);
    }

下面是我的 BaseResponse 类;

public class BaseResponse {

    private String code;

    private String message;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

下面是我的请求模型类;

@Entity
@Data
public class SchoolRequest {
        @Id
        @NotNull
        @JsonProperty("school")
        private String school;

调用下面的异常类;

  private void schoolRule(SchoolRequest schoolRequest) {
    
            if (schoolRequest.getSchool() == null || schoolRequest.getSchool().isEmpty()) {
                throw new BadRequestException("School can not be null or empty");
            }
        }

下面是我的 BadRequestException 类;

public class BadRequestException  extends RuntimeException{

    public BadRequestException(String message) {
        super(message);
    }

}

下面是我的控制器类;

public class SchoolController {

    private final School schoolService;

    @PostMapping(ApiPaths.schoolController.CTRL)
    public ResponseEntity<SchoolResponse> createSchool(@Valid @RequestBody SchoolRequest request) throws Exception {

        return schoolService.createSchool(request);
    }
}

我在下面收到的错误代码;

"code": "INTERNAL_SERVER_ERROR",
    "message": "Internal Server Error occured! Exception details: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<eu.demo.school.model.SchoolResponse> eu.demo.school.controller.SchoolController.createSchool java.lang.Exception: [Field error in object 'schoolRequest' on field 'school': rejected value [null]; codes [NotNull.schoolRequest.prefix,NotNull.prefix,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [schoolRequest.prefix,prefix]; arguments []; default message [school]]; default message [must not be null]]

【问题讨论】:

  • 您能否包括您的 SchoolService 课程和您收到的异常?

标签: java spring-mvc exception


【解决方案1】:

您的 ExceptionHandler 不会捕获所有异常。截至目前,它只捕获所有 BadRequestExceptions,而您收到的异常是 INTERNAL_SERVER_ERROR。问题是在您到达 schoolRule() 方法之前引发了不同的异常。

所以问题是抛出异常的位置。虽然我不能肯定地说没有看到 schoolService.createSchool(request); 内部发生的事情。以及 schoolRule(request) 是如何被调用的,我的猜测是它被你的 @NotNull 和 @Valid 注释所捕获。

“公共参数 [0] 验证失败”与 @Valid 提供的默认错误消息相同,因此我猜您还有其他代码将默认 MethodArgumentNotValidException 与您的自定义 INTERNAL_SERVER_ERROR 包装在一起。

如果我是正确的,您可能希望将 INTERNAL_SERVER_ERROR 添加到您的 ControllerAdvice 类中,尽管您也可以在调用 javax 验证器之前调用您的 schoolRule() 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2014-01-30
    相关资源
    最近更新 更多