GlobalHttpErrorHandlingMiddleware.ts 812 B

123456789101112131415161718192021222324252627282930313233
  1. /* eslint-disable @typescript-eslint/consistent-type-imports */
  2. import {
  3. Err,
  4. Middleware,
  5. Next,
  6. PlatformContext,
  7. PlatformResponse,
  8. } from '@tsed/common';
  9. /* eslint-enable @typescript-eslint/consistent-type-imports */
  10. import type { HttpError } from 'http-errors';
  11. import { isHttpError } from 'http-errors';
  12. @Middleware()
  13. export class GlobalHttpErrorHandlingMiddleware {
  14. use(
  15. @Err() err: unknown,
  16. @Next() next: Next,
  17. ctx: PlatformContext,
  18. ): PlatformResponse | undefined {
  19. // handle if the err is a HttpError instance
  20. if (isHttpError(err)) {
  21. const httpError = err as HttpError;
  22. const { response } = ctx;
  23. return response.status(httpError.status).body({
  24. status: httpError.status,
  25. message: httpError.message,
  26. });
  27. }
  28. next(err);
  29. }
  30. }