如何使用Spring Boot处理服务上的异常?

时间:2019-01-03 17:17:38

标签: spring spring-boot logging error-handling

我提供以下服务:

@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做到这一点?

1 个答案:

答案 0 :(得分:0)

尝试这个

@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;
    }
  }
}