The theory says: - if there is no error, return 200 - if there is an error, return 404 but how to pass error messages with the 404 code?
I have built a backend that currently returns code 200 AND in the json response there is a 'success' flag. If the flag is false, another field contains error message. (There may be several reasons why the operation failed and I want to display the reason to the user).
I am aware that by convention the 404 error should be returned but how can I pass the error message in that case ???
答案 0 :(得分:1)
如果没有错误,则返回200
,如果有错误,则返回corresponding error code and message
,而不仅仅是404
。找不到预期的数据或资源时,将收到404
。
您应该根据引发的错误来设置error message
字段的值。您可以catch
设置任何错误并将其设置为error message
,也可以针对各种错误生成自己的原因。
您的回复应该像
{
'success': false,
'errorCode' : 'code', //code returned by error
'errorMessage' : 'Custom Message' //error message
}
注意:通过编辑问题来发布一些代码,以便其他人可以更好地帮助您。
答案 1 :(得分:1)
如何通过以下两个主要部分来处理API结果:
HTTP错误响应:
请勿将其用于业务流程错误:
业务错误和失败的请求:
以200(确定)HTTP状态代码进行响应,并使用所需的响应格式,如下所示: