GlobalHttpErrorHandlingMiddleware.ts 685 B

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