-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: take full control over non-http exceptions
- Loading branch information
1 parent
849c1af
commit f6e5cee
Showing
2 changed files
with
58 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
src/modules/common/exception-filter/all-exceptions.filter.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { | ||
ExceptionFilter, | ||
Catch, | ||
ArgumentsHost, | ||
HttpException, | ||
HttpStatus, | ||
} from '@nestjs/common'; | ||
import { HttpAdapterHost } from '@nestjs/core'; | ||
import { QueryFailedError } from 'typeorm'; | ||
|
||
type ResponseBody = { | ||
statusCode: number; | ||
message: string | string[]; | ||
error: string; | ||
}; | ||
|
||
@Catch() | ||
export class AllExceptionsFilter implements ExceptionFilter { | ||
constructor(private readonly httpAdapterHost: HttpAdapterHost) {} | ||
|
||
catch(exception: unknown, host: ArgumentsHost): void { | ||
// In certain situations `httpAdapter` might not be available in the | ||
// constructor method, thus we should resolve it here. | ||
const { httpAdapter } = this.httpAdapterHost; | ||
|
||
const ctx = host.switchToHttp(); | ||
|
||
let statusCode: number; | ||
let responseBody: ResponseBody; | ||
|
||
// We now handle both HTTP and non-HTTP errors comprehensively. | ||
if (exception instanceof HttpException) { | ||
statusCode = exception.getStatus(); | ||
responseBody = exception.getResponse() as ResponseBody; | ||
} else if (exception instanceof QueryFailedError) { | ||
statusCode = HttpStatus.BAD_REQUEST; | ||
responseBody = { | ||
statusCode, | ||
message: exception.message, | ||
error: 'Database Query Failed Error', | ||
}; | ||
} else { | ||
statusCode = HttpStatus.INTERNAL_SERVER_ERROR; | ||
responseBody = { | ||
statusCode, | ||
message: (exception as Error).message, | ||
error: 'Internal Server Error', | ||
}; | ||
} | ||
|
||
httpAdapter.reply(ctx.getResponse(), responseBody, statusCode); | ||
} | ||
} |