Open yaofly2012 opened 4 years ago
Layer.prototype.handle_error
Layer.prototype.handle_error = function handle_error(error, req, res, next) {
var fn = this.handle;
if (fn.length !== 4) {
// not a standard error handler
return next(error);
}
try {
fn(error, req, res, next);
} catch (err) {
next(err);
}
};
error
作为第一个参数,有点类似nodejs的回调风格;this.handle
的形参数量是固定的,必须4个,要求规范化异常处理handler的格式;try-catch
捕获this.handle
的抛出的异常,并通过next(error)
方式处理异常。Layer.prototype.handle_request
Layer.prototype.handle_request = function handle(req, res, next) {
var fn = this.handle;
if (fn.length > 3) {
// not a standard request handler
return next();
}
try {
fn(req, res, next);
} catch (err) {
next(err);
}
};
this.handle
定义要求没那么苛刻了,只要形参不多于3个就行(4个视为异常处理handler);Layer.prototype.match
匹配路径字符串,并记录路径参数。
path-to-regexp
包要看看
Layer.prototype.match = function match(path) {
var match
// `null`和`void 0`是无效参数
if (path != null) {
// fast path non-ending match for / (any path matches)
if (this.regexp.fast_slash) {
this.params = {}
this.path = ''
return true
}
// fast path for * (everything matched in a param)
if (this.regexp.fast_star) {
this.params = {'0': decode_param(path)}
this.path = path
return true
}
// match the path
match = this.regexp.exec(path)
}
if (!match) {
this.params = undefined;
this.path = undefined;
return false;
}
// store values
this.params = {};
this.path = match[0]
var keys = this.keys;
var params = this.params;
for (var i = 1; i < match.length; i++) {
var key = keys[i - 1];
var prop = key.name;
var val = decode_param(match[i])
if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
params[prop] = val;
}
}
return true;
};
decode_param(val)
函数function decode_param(val) {
if (typeof val !== 'string' || val.length === 0) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = 'Failed to decode param \'' + val + '\'';
err.status = err.statusCode = 400;
}
throw err;
}
}
decodeURIComponent
操作如果发生异常,则给error
对象添加个status
属性,这个在哪里使用?项目中的异常处理是否也可采用这种模式?
layer.js
一、什么是
Layer
?Layer
是个执行者path-to-regexp
)request handler
ORerror handler
二、构造函数
Layer
Layer
是个构造函数,支持工厂函数方式调用。