Skip to content

Standardize error + flash responses #50184

Open

Description

@ojeytonwilliams

Currently the api-server sends errors messages back to the client in at least two ways. Either as a JSON response or as a query param. The former take the following shape:

{
  "message": "flash.updated-preferences",
  "type": "success",
  "variables": { "are": "optional" }
}

The query params are

{
  "messages": [ // elements have above shape ]
}

however, Fastify's default error responses are like this:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "body/profileUI must have required property 'isLocked'"
}

which is useful for debugging purposes.

However, we cannot send both JSON responses simultaneously. Also, we cannot merge the two, since we'd either lose the user friendly message (flash) or the detailed error message.

Issues to resolve

What do we want long term? Some combined object? For example:

{
  "statusCode": 400,
  "error": "Bad Request",
  "errorMessage": "body/profileUI must have required property 'isLocked'",
  "message": "flash.updated-preferences",
  "type": "success",
  "variables": { "are": "optional" }
}

What do we want to do in the interim? Defer fixing this until after the first release? Respond with the flash message data for now?

Activity

  1. added
    status: discussing
    on Apr 25, 2023
  2. ShaunSHamilton commented on Apr 25, 2023

    @ShaunSHamilton
    Member

    It might be nice to have a createResponse(code, message) function we had to use everywhere.

    function createResponse(code: number, message?: string): ReplyObject {
      // Attach code, use message or default
      return { ... };
    }

    After thinking about it, the flash system seems like something that should be entirely handled (logicked) on the client's side. The client should deal with defaults, and what kind of flash to show based on the error code and/or response message.

  3. ojeytonwilliams commented on Apr 25, 2023

    @ojeytonwilliams
    ContributorAuthor

    The client should deal with defaults, and what kind of flash to show based on the error code and/or response message.

    I.e. we can drop the 'type', because the client can see the status code? Sounds good.

    Otherwise, that's pretty much what we already have. Though possibly not with a sensible default.

  4. ShaunSHamilton commented on Apr 25, 2023

    @ShaunSHamilton
    Member

    Otherwise, that's pretty much what we already have.

    Well, yes. For the most part. However, I do not think we should be sending flash.<KIND> in message. We should send the raw info, and the client should be responsible for the "user readable" message.

  5. ojeytonwilliams commented on Apr 25, 2023

    @ojeytonwilliams
    ContributorAuthor

    Maybe, yeah. It depends if the client always has the info it needs (when you take the error code into account). I suspect that's not always the case, though.

    If it is the case, I'm all for letting the client handle that logic.

  6. moT01 commented on Apr 28, 2023

    @moT01
    Member

    I agree that, ideally, the client should handle what is displayed based on the response. The client should know what the user was attempting to do - i.e. Click "Save Privacy Settings" -> error -> display "Something went wrong trying to save your privacy settings"

    I think this would simplify the API. We should bring it up in the next meeting. I wonder if there's any messages that the server really does need to be in charge of. I can't think of any, but maybe... yea, I got nothin.

  7. Viksil11 commented on Apr 30, 2023

    @Viksil11
  8. huyenltnguyen commented on May 1, 2023

    @huyenltnguyen
    Member

    (I don't have enough context of the topic, but wanted to chime in anyway 😄)

    I think moving the display to the client side is also easier for localization as error/success messages would need to be translated as well.

    Though with statusCode and error alone, I don't think the client would be able to map to a user-friendly message, so we would still need errorMessage for additional information. Or if it's possible, maybe we could replace errorMessage with an errorReason property instead, which could be an enum and used in other operations on the server side.

  9. added this to the Backend API MVP milestone on Aug 17, 2023
  10. ShaunSHamilton commented on Aug 30, 2023

    @ShaunSHamilton
    Member

    Thinking about this more due to the Microsoft stuff where a single request can fail in so many ways, I think it would be nice to take a chapter out of IDLs, and have our error enums be something like:

    // utils/shareable-errors.ts
    // This will be defined by the API, but can be consumed by any clients
    
    enum MsError {
      InvalidLinkDomain = "The URL should match the 'learn.microsoft.com' domain",
      UncompletedModule = "One or more modules for this trophy have not been completed at 'learn.microsoft.com'"
    }

    Then, during the build, the shareable-errors.ts would be transpiled into:

    // Translatable error messages
    {
      "errors": [
        {
          "code": 0,
          "name": "InvalidLinkDomain",
          "msg": "The URL should match the..."
        },
        {
          "code": 1,
          "name": "UncompletedModule",
          "msg": "One or more..."
        }
      ]
    }
  11. moT01 commented on Sep 29, 2023

    @moT01
    Member

    Stick the flash in the response as its own property?

    {
      "statusCode": 400,
      "error": "Bad Request",
      "message": "body/profileUI must have required property 'isLocked'",
      "flash": {
        "type": "danger",
        "message": "flash.updated-preferences",
        "variables": { "user": "me" }
      }
    }
    
  12. ShaunSHamilton commented on Sep 29, 2023

    @ShaunSHamilton
    Member

    I think we should be going for as little information as required.

    I.e. we can drop the 'type', because the client can see the status code

    I would drop almost everything that is not default (Fastify/prisma), because the client should already be aware of the variables (request data).

  13. moT01 commented on Sep 29, 2023

    @moT01
    Member

    Perhaps that's the way to go. In theory, I like it - but just kind of thinking out loud...

    A possible response:

    {
      "statusCode": 400,
      "error": "Bad Request",
      "message": "body/profileUI must have required property 'isLocked'"
    }
    

    So then on the client we would have a lookup object or something?

    {
      "body/profileUI must have required property 'isLocked'": "flash.is-locked-err"
    }
    

    Seems like an extra step - but not terrible I guess. Do we know that the client will have access to all the variables? We have this endpoint for the MS trophies:

    const msUser = await MsUsername.findOne({
      where: { userId: user.id }
    });
    
    const { msUsername } = msUser;
    const msApiRes = await fetch(msTrophyApiUrl);
    const msTrophyJson = await msApiRes.json();
    
    if (!msApiRes.ok || msTrophyJson.awardType !== 'Trophy') {
      return res.status(403).json({
        type: 'error',
        message: 'flash.ms.trophy.err-3',
        variables: {
          msUsername
        }
      });
    }
    

    The client should have their MsUsername - but if it's different than the one found in the database, it could help us figure out what is going wrong?

  14. ShaunSHamilton commented on Sep 29, 2023

    @ShaunSHamilton
    Member

    but if it's different than the one found in the database, it could help us figure out what is going wrong?

    Good point. We should definitely be returning the relevant information. I suppose the current {message, variables} format is ok to keep.

    We should not be telling the client what to do, though (flash...). We could just have message: "4xx.ms.trophy-3":

    void res.statusCode(403); // Implies `type: "error"`
    return {
      message: "4xx.ms.trophy-3" // Notice the `4xx` implies `.err`
      variables: {
        msUsername
      }
    }
    {
      "4xx": {
        "ms": {
          "trophy-3": "Our usual format {{msUsername}}"
        }
      }
    }

    Then, we just need to publish our .json file with map to possible responses. Also, it would probably be better if we published some helper/package to use our custom format.

  15. ojeytonwilliams commented on Sep 29, 2023

    @ojeytonwilliams
    ContributorAuthor

    We shouldn't forget the human readable messages. 4xx.ms.trophy-3 doesn't mean anything to me.

  16. ShaunSHamilton commented on Sep 29, 2023

    @ShaunSHamilton
    Member

    We shouldn't forget the human readable messages. 4xx.ms.trophy-3 doesn't mean anything to me.

    We would still include whatever default comes with, but without duplicating info in two files, we either:
    a) Have 4xx.ms.trophy-3 and map it to a responses.json file
    b) Have fancy tooling that can automatically build all our responses { message: "Our usual format {{msUsername}}" } into a responses.json file for clients to consume.

    The only reason for this rigmarole is for i18n.

  17. ojeytonwilliams commented on Sep 29, 2023

    @ojeytonwilliams
    ContributorAuthor

    Sorry, I wasn't talking about the i18n. That's all reasonable, but I think we'll still want a message that we, as developers, can understand.

    So, in this hypothetical, we'd have

    {
      .. stuff
      "message": "userName missing from Microsoft transcript response"
    }

    That way we can see what the problem is without having to dig into the json.

  18. ShaunSHamilton commented on Sep 29, 2023

    @ShaunSHamilton
    Member

    Right,

    but without duplicating info in two files...

    Because then we would need to have:

    // script.ts
    return { message: "userName missing ...", mark: "4xx.ms.trophy-3" }
    // responses.json
    {
      "...trophy-3": "userName missing ..."
    }
  19. ojeytonwilliams commented on Sep 29, 2023

    @ojeytonwilliams
    ContributorAuthor

    I doubt it would be duplicated, because we'd want to send different info to developers and to users.

  20. moT01 commented on Sep 30, 2023

    @moT01
    Member

    I don't think I fully understand what some of these suggestions will look like - I still kinda like my earlier suggestion. Having the flash property in the response is more like a suggestion from the server - it's still up to the client to determine what to do with it. Also, it should be a pretty easy refactor on the client.

    void res.statusCode(403); // Implies type: "error"

    In most (maybe all) cases, this is accurate - but there may be an instance where we do want an 'info' style message when there's a 4xx error. The client could still override it and display the info style - but that seems like some potentially unnecessary extra logic on the client. It just seems simple to send a flash to client and then the client can just display it.

    I'm not sure if this needs to come into the discussion, but we do have endpoints that redirect. Could we make those more restful, by maybe adding a redirect property, and let the client do the redirecting? Or maybe we want to try and get rid of those or something.

    Whatever we decide, I would vote for whatever is the simplest, easiest to understand, and easiest to develop on.

  21. huyenltnguyen commented on Oct 24, 2023

    @huyenltnguyen
    Member

    We recently got an issue where the APIs return flash type as error but the client was expecting danger, causing an improper flash display: #51946.

    I'm wondering if the scope of this issue includes standardizing the value of flash type as well.

    If we go with error, we will need to update the Alert component in ui-components, which I don't mind doing. IMHO, error is more suitable than danger, even in the context of the component library alone.

    type AlertVariant = 'success' | 'info' | 'warning' | 'danger';

  22. ShaunSHamilton commented on Oct 24, 2023

    @ShaunSHamilton
    Member

    After more thinking: The API should not be in charge of any i18n. It should send through a message developers (clients) can understand, then it is up to the client what end-user string should be displayed.

    Otherwise, the API has to guess (think of) all the possible ways a client might use an endpoint in order to give an end-user the most useful message.


    Practically, this means the API does not even need to provide more than { standardError, customMessageForDevelopers }, where standardError is probably an instance of Error (i.e. just what you get when something throws).

    Also, we should not be providing any native (custom to) Fastify output in this response, because:
    a) The client should not need to be aware we use Fastify
    b) We should be agnostic to this level of tooling we use - easier migrations

  23. moT01 commented on Apr 30, 2024

    @moT01
    Member

    This feels post-mvp. Moved it to there, let me know if I shouldn't have.

  24. added
    status: on the roadmap
    and removed
    status: discussing
    on Aug 1, 2024
  25. KhiraHamdi commented on May 24, 2026

    @KhiraHamdi

    I found this issue still exists in the current codebase.
    In src/components/Flash/index.tsx line 20, the workaround
    mapping 'error' to 'danger' is still in place. The TODO
    comment confirms this needs standardization at the API level.
    Happy to help test any fix for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: on the roadmap

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions