首页 > 解决方案 > spring boot 中有没有办法手动调用异常建议?

问题描述

我有一个场景,其中一个已经存在的控制器和服务抛出异常,这些异常通过@RestControllerAdvice 处理。现在我有一个我已经介绍的新类,它以批处理模式从上述服务类调用方法。在我的课堂上,我必须捕获异常或成功将它们捆绑并返回。对于发生的任何异常,我需要报告 HTTP 状态和错误消息。您能否让我知道是否有任何方法可以实现这一目标?

标签: spring-bootexception

解决方案


您可以创建自己的Exception课程。

public class MyException extends Exception {

    private int errorCode;
    private String errorMessage;

    public MyException(int errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }
}

MyException并且您可以在发生任何异常时创建新的并抛出它。@RestControllerAdvice然后你在课堂上得到这个异常。

@RestControllerAdvice
public class ExceptionAdvice {

    private ErrorCodeMapper errorCodeMapper;

    @Autowired
    public ExceptionAdvice(ErrorCodeMapper errorCodeMapper) {
        this.errorCodeMapper = errorCodeMapper;
    }

    @ExceptionHandler(value = MyException.class)
    public ResponseEntity handleGenericNotFoundException(MyException e) {
        return new ResponseEntity(errorCodeMapper.getStatusCode(e.getErrorCode()));
    }
}

和映射器类如下:

@Service
public class ErrorCodeMapper {

    public static Map<Integer,HttpStatus> errorCodeMap = new HashMap<>();
    public ErrorCodeMapper(){
        errorCodeMap.put(100, HttpStatus.BAD_REQUEST);
        errorCodeMap.put(101,HttpStatus.OK);
        errorCodeMap.put(102,HttpStatus.BAD_REQUEST);
        errorCodeMap.put(103,HttpStatus.BAD_REQUEST);
    }

    HttpStatus getStatusCode(int errorCode){
        return errorCodeMap.get(errorCode);
    }
}

您可以将更多详细信息MyException添加到ResponseEntity.


推荐阅读