GlobalHttpErrorHandlingMiddleware.ts 650 B

123456789101112131415161718192021222324252627
  1. import {
  2. Err, Middleware, Next, PlatformContext, PlatformResponse,
  3. } from '@tsed/common';
  4. import { HttpError, isHttpError } from 'http-errors';
  5. @Middleware()
  6. export class GlobalHttpErrorHandlingMiddleware {
  7. use(@Err() err: unknown, @Next() next: Next, ctx: PlatformContext): PlatformResponse<any>|void {
  8. // handle if the err is a HttpError instance
  9. if (isHttpError(err)) {
  10. const httpError = err as HttpError;
  11. const { response } = ctx;
  12. return response
  13. .status(httpError.status)
  14. .body({
  15. status: httpError.status,
  16. message: httpError.message,
  17. });
  18. }
  19. next(err);
  20. }
  21. }