【问题标题】:How do I handle exception on a service with spring boot?如何使用 Spring Boot 处理服务异常?
【发布时间】:2019-01-03 17:17:38
【问题描述】:

我有以下服务:

@Service
public class MyService {

  private static final Logger LOG = LoggerFactory.getLogger(MyService.class);
  private ObjectMapper objectMapper = new ObjectMapper();

  @JmsListener(destination = "queue")
  public void receiveMessage(String message) throws JMSException, IOException {
    LOG.info("Got message:  " + message);
    MyObject obj = objectMapper.readValue(message, MyObject.class);
    LOG.info("Object Name " + obj.getName());
  }
}

如果receiveMessage 抛出错误,我想将此错误记录到日志文件中。如何使用 Spring Boot 执行此操作?

【问题讨论】:

  • 你可以使用 try 和 catch 块。

标签: spring spring-boot logging error-handling


【解决方案1】:

试试这个

@Service
public class MyService {

  private static final Logger LOG = LoggerFactory.getLogger(MyService.class);
  private ObjectMapper objectMapper = new ObjectMapper();

  @JmsListener(destination = "queue")
  public void receiveMessage(String message) throws JMSException, IOException  {
    try{
        LOG.info("Got message:  " + message);
        MyObject obj = objectMapper.readValue(message, MyObject.class);
        LOG.info("Object Name " + obj.getName());
    }catch (JMSException |  IOException e){
      LOG.error(e.getMesage(),e);
      throw e;
    }
  }
}

【讨论】:

  • 它已经捕获了 JMS 和 IO 异常,那么为什么要在方法签名中声明 throws JMSException、IOException。
  • 它捕获异常、日志和抛出。重新抛出异常是为了防止级联效应,这意味着如果出现问题并且不抛出异常调用将移动到链中的下一个方法,这在某些时候不应该是可取的。为了防止重新抛出异常。
  • 如果你认为不是这样,你可以更改方法签名并且不要重新抛出
猜你喜欢
  • 2022-06-19
  • 2018-03-16
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
相关资源
最近更新 更多