Last active
August 29, 2015 14:22
-
-
Save mike-gusiev/97fb8899bff00115d5fc to your computer and use it in GitHub Desktop.
NodeJS tips
This file contains 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 util = require('util'); | |
var phrases = { | |
"Hello" : "Привет", | |
"world" : "Мир" | |
} | |
function PhraseError(message) { | |
this.message = message; | |
Error.captureStackTrace(this, PhraseError); //сохраняем стек ошибки | |
} | |
util.inherits(PhraseError, Error); | |
PhraseError.prototype.name = 'PhraseError'; | |
function HttpError(status, message) { | |
this.status = status; | |
this.message = message; | |
} | |
util.inherits(HttpError, Error); | |
HttpError.prototype.name = 'HttpError'; | |
function getPhrases(name) { | |
if(!phrases[name]) { | |
throw new PhraseError("Нет такой фразы: " + name); //HTTP 500, уведомление! | |
} | |
return phrases[name]; | |
} | |
function makePage(url) { | |
if(url != 'index.html') { | |
throw new HttpError(404, "Нет такой страницы"); //HTTP 404 | |
} | |
return util.format("%s, %s!", getPhrases("Hello"), getPhrases("world")); | |
} | |
try { | |
var page = makePage("index.html"); | |
console.log(page); | |
} catch(e) { | |
if(e instanceof HttpError) { | |
console.log(e.status, e.message); | |
} else { | |
console.error("Ошибка %s\n сообщение: %s\n стек: %s", e.name, e.message, e.stack); | |
} | |
} |
This file contains 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 log = require('logger')(module); | |
module.exports = function (module) { | |
return function (/* ... */) { | |
var args = [module.filename].concat([].slice.call(arguments)); | |
console.log.apply(console, args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment