Should service methods throw exceptions?

Should service methods throw exceptions?

The answer is no. Services should expose errors in a general way. In the case of Restful service, errors should be propagated as HTTP status with error codes.

Where should you catch exceptions?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let’s say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.

Should I catch exception controller?

Contrary to the opinion that throwing exceptions from Controller handler methods is bad, I do recommend to do so. The reasons are following: It eliminates a lot of boilerplate code. Almost all try-catches in controllers are the same and are frequently copy-pasted from one place to another.

When to wrap exceptions in a service layer?

However, for public facing code; service that are consumed by a third party or customer, I think it is cleaner to wrap any unchecked exceptions with a service oriented exception, primarily for security concerns, secondly for loose coupling, and clean abstraction.

What should service layer catch all DAO exceptions and?

The client should be allowed to deal with any checked/expected exceptions that it can handle, and treat everything else as a potential bug report. Your service contract should be an atomic, consistent, transactional abstraction. If it can’t do anything about the exception, then the only useful thing left is to give you a bug report.

How to avoid throwing the same exception in different places?

It is common for a class to throw the same exception from different places in its implementation. To avoid excessive code, use helper methods that create the exception and return it. For example: In some cases, it’s more appropriate to use the exception’s constructor to build the exception.

When to not catch an exception in a catch block?

In catch blocks, always order exceptions from the most derived to the least derived. All exceptions derive from Exception. More derived exceptions are not handled by a catch clause that is preceded by a catch clause for a base exception class. When your code cannot recover from an exception, don’t catch that exception.