Avoiding exceptions vs handling exceptions in Java [on hold]

问题: I am implementing a DELETE rest endpoint in spring boot, I am not sure which approach is better between below 2 approaches: First checking if the record with given Id...

问题:

I am implementing a DELETE rest endpoint in spring boot, I am not sure which approach is better between below 2 approaches:

  1. First checking if the record with given Id exists in the database and then delete it safely.

  2. Directly calling delete on spring data repository and catching EmptyResultDataAccessException thrown by spring data to return 404 response.

I like the first one as the code is more readable and does not involve controlling flow using exceptions. However, it involves an additional call to db and potential race condition.

Why would you prefer the first or the second approach?


回答1:

If you annotate the service method with @Transactional there will be no race condition and it's fine to check for existence first (with a small performance overhead).

On the other hand I always like the simplicity of attempting the deletion and catching the exception, the assumption being that deleting a non-existent resource is exceptional.

Note also that in REST a DELETE on a non-existing resource should normally return a succesful HTTP status code 200 (OK) or 204 (NO_CONTENT).

@Transactional
public Response deleteAfterChecking(Thing thing) {
    if (!repository.exists(thing)) {                        
        repository.delete(thing);            
    }
    return Response.NO_CONTENT;
}

public Response deleteHandlingException(Thing thing) {
    try {               
        repository.delete(thing);            
    }
    catch (NotFoundException e) {
        // do nothing
    }
    return Response.NO_CONTENT;
}

回答2:

The first option is better conventions-wise and will be more readable, but not performance-wise on big amounts of data as you will need two calls. Indeed, you should not need to catch an EmptyResultDataAccessException at any point.

You should nonetheless think about your code conception. How can the ID of a potentially non-persisted object be passed ? Is it necessary ? Without your code, I can't judge, but I believe you should consider this.

  • 发表于 2019-03-01 00:48
  • 阅读 ( 174 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除