Laravel:如何从API向客户端发送自定义错误消息?

huangapple go评论66阅读模式
英文:

Laravel: How to send custom error messages to client from API?

问题

我有一个Laravel API,向客户端返回JSON响应。默认情况下,Laravel以标准格式发送错误消息,例如422 Unprocessable Entity。然而,我想以特定格式向客户端发送自定义错误消息,例如:

{
    "status": "error",
    "message": "Invalid email address"
}

我尝试使用abort函数并自定义状态码和消息,但这不会以所示格式发送响应。如何以上面显示的格式向客户端发送自定义错误消息?

英文:

I have a Laravel API that returns JSON responses to the client. By default, Laravel sends error messages in a standard format, such as 422 Unprocessable Entity. However, I want to send custom error messages to the client in a specific format, for example:

{
    "status": "error",
    "message": "Invalid email address"
}

I have tried using the abort function with a custom status code and message, but this does not send the response in the desired format. How can I send custom error messages to the client in the format shown above?

答案1

得分: 3

Many possible solutions for you. Have a look at this discussion for example.

您有许多可能的解决方案。例如,可以参考此处的讨论。

You can create your own validators, or just extend on the existing ones built in Laravel. Also, it's very possible to return whatever else you need with for example:

您可以创建自己的验证器,或者只是扩展Laravel中已有的验证器。此外,您也可以很容易地返回您需要的任何其他内容,例如:

return response()->json(['status' => 'error', 'message' => 'Your message here'], 422);

但如果您需要它进行验证,我建议按照先前提到的步骤,因为它们遵循更标准化的“良好实践”方法。

但如果您需要它进行验证,我建议按照先前提到的步骤,因为它们遵循更标准化的“良好实践”方法。

Also, when sending the request, make sure you set the following header:

另外,在发送请求时,请确保设置以下标头:

Accept: application/json

You can also "force" that header using a middleware in Laravel if needed. Link here

如果需要的话,您还可以使用Laravel中的中间件“强制”该标头。链接在此处

英文:

Many possible solutions for you. Have a look at this discussion for example.

You can create your own validators, or just extend on the existing ones built in Laravel. Also, it's very possible to return whatever else you need with for example:

return response()->json(['status' => 'error', 'message' => 'Your message here'], 422);

But if you need it for validation, I would recommend other previously mentioned steps as they follow a more standardized "good practice" approach.

Also, when sending the request, make sure you set the following header:

Accept:application/json

You can also "force" that header using a middleware in Laravel if needed. Link here

huangapple
  • 本文由 发表于 2023年5月8日 00:57:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定