Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ErrorMiddleware): Only respect certain err.statuses #199

Merged
merged 4 commits into from
Aug 25, 2023

Conversation

72636c
Copy link
Member

@72636c 72636c commented Aug 24, 2023

BREAKING CHANGE: Some HTTP clients throw errors with a status property to indicate the status code of the HTTP response. If such an error was not handled by a middleware or controller further up the chain, ErrorMiddleware.handle would previously pick up the error and reflect its status code back to your client.

Most of the time, this is not what you want. For example, if your server depends on an upstream service-to-service endpoint and it starts to respond with HTTP 401s, that may imply that your server is not appropriately authenticated and is at fault, and should default to a HTTP 500. This is now the default behaviour of ErrorMiddleware.handle.

If you want to throw an error that ErrorMiddleware.handle will pick up to modify your response status code, you are now limited to three options:

  1. Use http-errors

    import createError from 'http-errors';
    
    const controller = () => {
      throw new createError.ImATeapot();
    };
  2. Use ctx.throw

    const controller = (ctx) => {
      ctx.throw(418, 'Badness!');
    };
  3. Include isJsonResponse and status properties on your error

    class MyCustomError extends Error {
      constructor(
        message: string,
        public isJsonResponse: boolean,
        public status: number,
      ) {
        super(message);
    
        this.isJsonResponse = isJsonResponse;
        this.status = status;
      }
    }
    
    const controller = () => {
      throw new MyCustomError('Badness!', false, 418);
    };

@72636c 72636c marked this pull request as ready for review August 25, 2023 00:53
@72636c 72636c requested a review from a team as a code owner August 25, 2023 00:53
@72636c 72636c merged commit 591fb75 into master Aug 25, 2023
5 checks passed
@72636c 72636c deleted the limit-err-statuses branch August 25, 2023 02:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants