سؤال

I have a Web API, and I'm thinking if it's a good idea to always wrap the result with a my own result model which will always contain specific structure like:

{
 Data:(of type T generic),
 Messages:[ 
   {Key:"Key1",Messages:["Msg1","Msg2","Msg3"]},
   {Key:"Key2",Messages:["Msg1","Msg2","Msg3"]},
  ],
 MetaData:[ 
   {Key:"",Value:"" },
   {Key:"",Value:"" }
  ]
}

So I see this model is suitable for all situations, for example:

  1. I want to return success 20x with data only, I just fill Data property only and leave the others empty.
  2. If I want to return failure status with some messages (from Model state or any other) I just fill Messages.

So I always return my model.
Is this considered as good practice, or should I return different model depending on each status (success or failure).

Thanks

Update 1:
Status codes will still be used to determine if the messages inside the model are error messages or just warning or maybe info, what I'm asking here to abandon the using of Status Codes but:

is it a best practice to use unified model in all my responses, maybe some times I need to response as BadRequest with data returned with the messages.

هل كانت مفيدة؟

المحلول

I believe in web api You should stick to the conventions and use http error codes to indicate failure.

Think how would You treat Your message on the receiving side:

  • You would have to write some kind of logic to really detect whether You got an error or success.

  • You would have to explain the convention to other developers using the code.

I would say this is a bit of reinventing the wheel. In my team we simply use HTTP status codes with messages to report error and it seems to be working well. It's also simpler to handle it with certain web related libraries we're using on client side.

Edit after question update: In my opinion this really comes down to particular use case. If You think about using this pattern always starting from now then I would not go into it.

If You intend to introduce it in a particular service or product and it is really true (which means there is a use case or requirement) that You will have to return some data together with an error code that's fine. In this case I don't see any better solution.

نصائح أخرى

Consider returning error messages of some kind, if something went wrong. Returning a model even though an error occurred is probably not the best practice.

For example, when no data was found, returning null instead is often better practice.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top