错误处理
¥Error handling
Strapi 本身就以标准格式处理错误。
¥Strapi is natively handling errors with a standard format.
错误处理有 2 个用例:
¥There are 2 use cases for error handling:
-
作为通过 REST 或 GraphQL API 查询内容的开发者,你可能会 接收错误 来响应请求。
¥As a developer querying content through the REST or GraphQL APIs, you might receive errors in response to the requests.
-
作为自定义 Strapi 应用后端的开发者,你可以使用 抛出错误 的控制器和服务。
¥As a developer customizing the backend of your Strapi application, you could use controllers and services to throw errors.
接收错误
¥Receiving errors
错误包含在带有 error
键的响应对象中,并包含 HTTP 状态代码、错误名称和其他信息等信息。
¥Errors are included in the response object with the error
key and include information such as the HTTP status code, the name of the error, and additional information.
REST 错误
¥REST errors
REST API 引发的错误包含在具有以下格式的 response 中:
¥Errors thrown by the REST API are included in the response that has the following format:
{
"data": null,
"error": {
"status": "", // HTTP status
"name": "", // Strapi error name ('ApplicationError' or 'ValidationError')
"message": "", // A human readable error message
"details": {
// error info specific to the error type
}
}
}
GraphQL 错误
¥GraphQL errors
GraphQL API 抛出的错误包含在具有以下格式的响应中:
¥Errors thrown by the GraphQL API are included in the response that has the following format:
{ "errors": [
{
"message": "", // A human reable error message
"extensions": {
"error": {
"name": "", // Strapi error name ('ApplicationError' or 'ValidationError'),
"message": "", // A human reable error message (same one as above);
"details": {}, // Error info specific to the error type
},
"code": "" // GraphQL error code (ex: BAD_USER_INPUT)
}
}
],
"data": {
"graphQLQueryName": null
}
}
投掷错误
¥Throwing errors
控制器和中间件
¥Controllers and middlewares
使用 Strapi 开发任何自定义逻辑时抛出错误的推荐方法是让 controller 或 中间件 以正确的状态和正文进行响应。
¥The recommended way to throw errors when developing any custom logic with Strapi is to have the controller or middleware respond with the correct status and body.
这可以通过在上下文(即 ctx
)上调用错误函数来完成。可用的错误函数列在 http 错误文档 中,但它们的名称应采用小写驼峰格式以供 Strapi 使用(例如 badRequest
)。
¥This can be done by calling an error function on the context (i.e. ctx
). Available error functions are listed in the http-errors documentation but their name should be lower camel-cased to be used by Strapi (e.g. badRequest
).
错误函数接受 2 个参数,对应于开发者查询 API 的 error.message
和 error.details
属性 received:
¥Error functions accept 2 parameters that correspond to the error.message
and error.details
attributes received by a developer querying the API:
-
该函数的第一个参数是错误
message
¥the first parameter of the function is the error
message
-
第二个是将在收到的响应中设置为
details
的对象¥and the second one is the object that will be set as
details
in the response received
- JavaScript
- TypeScript
// path: ./src/api/[api-name]/controllers/my-controller.js
module.exports = {
renameDog: async (ctx, next) => {
const newName = ctx.request.body.name;
if (!newName) {
return ctx.badRequest('name is missing', { foo: 'bar' })
}
ctx.body = strapi.service('api::dog.dog').rename(newName);
}
}
// path: ./src/api/[api-name]/middlewares/my-middleware.js
module.exports = async (ctx, next) => {
const newName = ctx.request.body.name;
if (!newName) {
return ctx.badRequest('name is missing', { foo: 'bar' })
}
await next();
}
// path: ./src/api/[api-name]/controllers/my-controller.ts
export default {
renameDog: async (ctx, next) => {
const newName = ctx.request.body.name;
if (!newName) {
return ctx.badRequest('name is missing', { foo: 'bar' })
}
ctx.body = strapi.service('api::dog.dog').rename(newName);
}
}
// path: ./src/api/[api-name]/middlewares/my-middleware.ts
export default async (ctx, next) => {
const newName = ctx.request.body.name;
if (!newName) {
return ctx.badRequest('name is missing', { foo: 'bar' })
}
await next();
}
服务和模型生命周期
¥Services and models lifecycles
一旦你在比控制器或中间件更深的层上工作,就会有专用的错误类可用于引发错误。这些类是 节点 `Error` 类 的扩展,专门针对某些用例。
¥Once you are working at a deeper layer than the controllers or middlewares there are dedicated error classes that can be used to throw errors. These classes are extensions of Node `Error` class and are specifically targeted for certain use-cases.
这些错误类是通过 @strapi/utils
包导入的,并且可以从多个不同的层调用。以下示例使用服务层,但错误类不仅限于服务和模型生命周期。在模型生命周期层中抛出错误时,建议使用 ApplicationError
类,以便在管理面板中显示正确的错误消息。
¥These error classes are imported through the @strapi/utils
package and can be called from several different layers. The following examples use the service layer but error classes are not just limited to services and model lifecycles. When throwing errors in the model lifecycle layer, it's recommended to use the ApplicationError
class so that proper error messages are shown in the admin panel.
有关 Strapi 提供的错误类别的更多信息,请参阅 默认错误类别 部分。
¥See the default error classes section for more information on the error classes provided by Strapi.