spring-boot - spring boot 中有没有办法手动调用异常建议?
问题描述
我有一个场景,其中一个已经存在的控制器和服务抛出异常,这些异常通过@RestControllerAdvice 处理。现在我有一个我已经介绍的新类,它以批处理模式从上述服务类调用方法。在我的课堂上,我必须捕获异常或成功将它们捆绑并返回。对于发生的任何异常,我需要报告 HTTP 状态和错误消息。您能否让我知道是否有任何方法可以实现这一目标?
解决方案
您可以创建自己的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
.
推荐阅读
- stm32 - 我可以得到简单的代码来发送数据到液晶显示器 我可以得到简单的代码来发送数据到液晶显示器吗
- cupy - 在 TX2 上运行 cupy
- python - 使用 tf.keras.applications.MobileNetV2 训练失败
- c++ - 如何在 Visual Studio 中使用 Resource.RC 文件
- python - 如何在 IIS 服务器中配置 Flask 应用程序?
- javascript - 在 highcharts 中,是否可以在柱形图中制作一个条形图,其顶部与图表边界“顶部”的图表区域边缘接壤?
- python - 如何导入pybind11生成的二进制模块?
- docker - Docker 容器启动失败,如果它有 Docker 机密
- javascript - 没有找到 P5 DOM 函数“选择”,即使我已经导入了 p5.dom.js
- angular - 'E/launcher - 错误:尝试从 Jenkins(Unix 机器)运行量角器测试时产生 EACCES 错误