When to use custom exceptions vs. existing exceptions vs. generic exceptions

后端 未结 5 2076
遥遥无期
遥遥无期 2020-12-14 04:05

I\'m trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a st

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 04:32

    You have two species of exceptions.

    Those that are specific to your application, where it's good to avoid any existing exceptions.

    Your application-specific exceptions should simplify the use cases for the folks who use your libraries. 3 of your application specific exceptions are things users can do. The fourth (badge does not exist) is clearly not procedural, but far more serious.

    It looks like you have two application-specific errors: user-oriented things and administrative mistakes.

    The others are part of some other piece of technology; i.e., database errors. You can -- generally -- ignore these. If the DB isn't available, the API will throw errors and you can let those bubble up through your library.

    You can also "wrap" these as an application-specific exception which contains a lower-level exception. This is sometimes helpful if there is a lot of lower-level technology. In your case, it's just a database. Ignore it and let the DB errors bubble through.

提交回复
热议问题