Is it good way to throw error from service in nestjs like it:
In general it's a good idea to throw business errors from your services and handle theses errors on controller layer. But there is room for improvement looking at your code:
To me it looks a bit odd to stringify the message
and status
in order to pass it to Error
. You could create a custom Error that contains these properties:
class MyBusinessError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
But I suggest to decide on controller level which status should be returned from the API because this is http specific and should not be part of your business logic.
Also there are exception filters coming with NestJS that you can use to catch exceptions and transform them into http exceptions. With that you don't need to try-catch in every controller method.
You can check for specific Error type using instanceof
:
try {
// ...
}
catch(err) {
if(err instanceof MyBusinessError) {
// handle business error
}
throw err;
}