EggBornJS unifies the return result of API Routes
. It injects the following methods into the object of ctx
:
Name | Description |
---|---|
ctx.success | return successful result |
ctx.successMore | return successful result which is paged |
ctx.fail | return error result |
ctx.throw | throw exception |
ctx.success
Return the successful data, which is usually invoked in Controller
const res = 'done';
this.ctx.success(res);
The result is:
{
"code": 0,
"message": "Success",
"data": "done"
}
ctx.successMore
Return the successful data with paged info, which is usually invoked in Controller
For example, read the first page, 10 items per page:
const page = { index: 0, size: 10 };
const items = [
{ id: 1, name: 'name1' },
{ id: 2, name: 'name2' }
];
this.ctx.successMore(items, page.index, page.size);
The result is:
{
"code": 0,
"message": "Success",
"data": {
"list": [
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
],
"index": 2,
"finished": true
}
}
Name | Description |
---|---|
data.list | the list of data |
data.index | list offset, used to read next page data |
data.finished | idendify whether the list data has been read completely. If so, the next page will not be read any more |
ctx.fail
Return the error result, which is usually invoked in Controller
Definition of Error Code
EggBornJS is compatible with HTTP error codes, such as 403
, 404
, etc. In addition, you can customize the new error codes and the corresponding error messages
src/suite-vendor/test-party/modules/test-party/backend/src/config/errors.js
// error code should start from 1001
module.exports = {
1001: 'Error Test',
};
Error Messages
also support i18n
. You only need to add corresponding language resources
src/suite-vendor/test-party/modules/test-party/backend/src/config/locale/zh-cn.js
module.exports = {
'Error Test': '错误测试',
};
Return error result
Same Module
this.ctx.fail(1001);
Across Module
this.ctx.fail.module('test-party',1001);
The Result
{
"code": 1001,
"message": "错误测试"
}
ctx.throw
Throw exception, and return the error message to frontend
Definition of Error Code
Same as ctx.fail
Throw exception
Same Module
this.ctx.throw(1001);
Across Module
this.ctx.throw.module('test-party',1001);
The Result
{
"code": 1001,
"message": "错误测试",
"stack": "Error: 错误测试\n at ErrorClass.throw ...",
"name": "Error",
"status": 500
}
Comments: