updated at : 2019/12/23

MVC, 클린아키텍쳐 등 레이어를 나누고 각 레이어별 책임을 다하는 app에 대해서 에러핸들링을 어떻게 하는것이 제일 좋을까에 대한 주저리

Error Handling in the Real World - Portland Python User Group

Error Handling Should I throw exception? Or handle at the source?

7 Common Mistakes You Should Avoid When Handling Java Exceptions

Custom exceptions with context | Holger Woltersdorf's blog

[코드리뷰] Exception 처리

내가 갖고 있는 의문들

  1. 왜 Exception으로 안 잡고 개별 Exception으로 잡아야하는가?

    → Exception으로 잡아서 거기서 에러 코드(에러메세지)만 읽어도 확인할 수 있지않은가?

    에러를 구조화 하여 접근해야 나중에 문제 풀기가 편하다

  2. 에러를 잡고 무엇을 하는가?

    → 어차피 에러 잡고서 그냥 로그 남기고 땡 아닌가...?

    기능에서 요구하는 사항 중 에러 사항에 대한 행동이 있을 것이다. 이거를 해야함

  3. 위로 올려서(throw) 해서 무엇하는가?

    → 뭐 정보를 적어서 올리라는데, 뭘 적어서 올리는가?

    이를 처리할 레이어에서 알고 있으면 좋은 정보들. 예를 들어 input이 제대로 안됬을 경우 해당 필드들의 값들이 뭔지 알아야 하지 않을까?

  4. controller → useCase → repository 로 구성된 레이어고, 이 방식대로 호출한다고 할 경우

    → controller에서만 try/catch를 해주면 되는 것 아닌가?

    책임을 어떻게 구성하느냐에 따라 달라질듯.

    다만 최하단 레이어에서 무작정 try-catch를 사용하는 것은 앞으로 지양해야할 듯.

  5. 모든 메서드마다 try/catch를 해줘야 하는가?? → No

try-catch(except) 의 원칙

<aside> 💡 catch를 한다는 것은 에러를 잡아서 여기에 무언가 작업을 하기 위함임. 단순히 잡고 로그 남기고 다시 위로 throw 하는것은 잘못된 방식

</aside>

In your example, it is unlikely that upper layers can do anything about an SQLite exception (if they do, then it is all so coupled to SQLite that you won't be able to switch the data layer to something else). There are a handful of foreseeable reasons for things like Add/Delete/Update to fail, and some of them (incompatible changes in concurrent transactions) are impossible to recover from even in the data/persistence layer (violation of integrity rules, f.i.). The persistence layer should translate the exceptions to something meaningful in the model layer terms so upper layers can decide if to retry or to fail gracefully.

Good use of try catch-blocks?

무엇을 잡아야 하는가?