Commit c67fd001 authored by Lorex's avatar Lorex

feat: 統一輸出並加入 error code 機制

parent 234f3822
const e = sails.config.errcode.code;
module.exports = function err(optionalData) {
// Get access to `req` and `res`
var req = this.req;
var res = this.res;
// Define the status code to send in the response.
var statusCodeToSet = 400;
// If no data was provided, use res.sendStatus().
if (optionalData === undefined) {
sails.log.info('Ran custom response: res.trnError()');
return res.sendStatus(statusCodeToSet);
}
if (e[optionalData] === undefined) {
sails.log.info('Custom response `res.trnError()` called with an Error: Error code not exists.');
return res.status(statusCodeToSet);
}
const resData = {
status: e[optionalData].status,
msg: e[optionalData].msg
};
// Set status code and send response data.
return res.status(resData.status).send({
success: false,
msg: resData.msg
});
};
/**
* Module dependencies
*/
var util = require('util');
var _ = require('@sailshq/lodash');
/**
* 200 (OK) Response
*
* Usage:
* return res.ok();
* return res.ok(data);
*
* @param {JSON?} data
* @param {Ref?} noLongerSupported
*/
module.exports = function ok(data, noLongerSupported) {
// Get access to `req` and `res`
var req = this.req;
var res = this.res;
// Get access to `sails`
var sails = req._sails;
// If a second argument was given, log a message.
if (noLongerSupported) {
sails.log.debug('The second argument to `res.ok()` is deprecated.');
sails.log.debug('To serve a view via `res.ok()`, override the response');
sails.log.debug('in \'api/responses/ok.js\'.\n');
}
// Set status code
res.status(200);
// Extreme edge case (very rare to pass an Error into res.ok() -- but still, just in case)
// If the data is an Error instance and it doesn't have a custom .toJSON(),
// then util.inspect() it instead (otherwise res.json() will turn it into an empty dictionary).
// > Note that we don't do this in production, since (depending on your Node.js version) inspecting
// > the Error might reveal the `stack`. And since `res.ok()` could certainly be used in
// > production, and it could inadvertently be passed an Error instance, we censor the stack trace
// > as a simple failsafe.
if (_.isError(data)) {
if (!_.isFunction(data.toJSON)) {
if (process.env.NODE_ENV === 'production') {
return res.sendStatus(200);
}
// No need to JSON stringify (it's already a string).
return res.send(util.inspect(data));
}
}
return res.json({
success: true,
data
});
};
module.exports.errcode = {
code: {
//- 900: 操作相關
900: {
msg: '操作失敗:尚未登入',
status: 401
}
}
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment