Created
April 19, 2014 01:24
-
-
Save ishiduca/11070752 to your computer and use it in GitHub Desktop.
第一引数にエラーが渡されるコールバック関数からエラー処理を退避させる ref: http://qiita.com/ishiduca/items/58459548a9c9bf5b6f0a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function (global) { | |
'use strict' | |
var isBrowser = !! global.self | |
var isWorker = !! global.WorkerLocation | |
var isNodeJS = !! global.global | |
function Domain () {} | |
Domain.prototype.intercept = function (cb, she) { | |
var me = this | |
return function () { | |
var args = [].slice.apply(arguments) | |
var err = args.shift() | |
err ? (typeof me.onError === 'function' && me.onError(err)) | |
: cb.apply(she, args) | |
} | |
} | |
if (isNodeJS) { | |
module.exports = Domain | |
} else { | |
global.Domain = Domain | |
} | |
})(this.self || global) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onError (err) { console.log(err.stack || err.toString()) } | |
var reg = /[0-9a-zA-Z._\-]+@[0-9a-zA-Z._\-]+?\.org/g | |
var x = new XMLHttpRequest | |
x.addEventListener('load', function () { | |
parse(x.responseText, reg, function (err, list) { | |
if (err) return onError(err) | |
// 正常なケースの処理 | |
some_works(list) | |
}) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var d = new Domain | |
d.onError = function (err) { console.log(err.stack || err.toString()) } | |
var reg = /[0-9a-zA-Z._\-]+@[0-9a-zA-Z._\-]+?\.org/g | |
var x = new XMLHttpRequest | |
x.addEventListener('load', function () { | |
parse(x.responseText, reg, d.intercept(function (list) { | |
// 正常なケースの処理 | |
some_works(list) | |
})) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 文字列から正規表現にマッチしたリストを第2引数に渡す: 正常な値として | |
// マッチしない場合はエラーを第1引数に渡す: エラーケースとして | |
function parse (str, reg, cb) { | |
var res, list = [] | |
try { | |
while (res = reg.exec(str)) { | |
list.push(res) | |
} | |
} catch (err) { return cb(err) } | |
if (list.length === 0) { | |
return cb(new Error('string did not match regular.')) | |
} | |
cb(null, list) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment