It is especially useful for clean architecture. When we make exceptions per layer, we can chain them keeping original information.
This concept is already well-known among server-side engineers. As an example, let's show the implementation of PHP in the Laravel Framework as JavaScript code.
class UserRepository extends Repository {
find(id) {
// return User or null
}
findOrFail(id) {
const user = this.find(id);
if (!user) {
throw new ModelNotFoundException(`User [${id}} not found.`);
}
return user;
}
}
class ExceptionHandler
{
render(e) {
if (e instanceof AuthenticationException) {
return new HttpException(401, e);
}
if (e instanceof AuthorizationException) {
return new HttpException(403, e);
}
if (e instanceof ModelNotFoundException) {
return new HttpException(404, e);
}
return new HttpException(500, e);
}
}
ModelNotFoundException indicates that the Model corresponding to ID was not found, but it does not have any HTTP status information. ExceptionHandler wrap it with HttpException to append HTTP 404 status information.