SORU
5 EYLÜL 2011, PAZARTESİ


Node.js En İyi Özel Durum İşleme Uygulama

Ben sadece node.js birkaç gün önce denemeye başladı. Düğüm programım işlenmeyen bir özel durum var ne zaman sona olduğunu fark ettim. Bu işlenmeyen özel durumlar ortaya kabın hala istek almak için mümkün olacağını zaman sadece iş Parçacığı öldüğü maruz kaldım normal server konteyner farklıdır. Bu birkaç soru yükseltir:

  • process.on('uncaughtException') tek etkili şekilde karşı korumak için mi?
  • process.on('uncaughtException') zaman uyumsuz işlemler yürütülürken işlenmeyen bir özel durum da yakalayacak?
  • Zaten yapabileceğim inşa (e-posta gönderme veya bir dosyaya yazma gibi) bir modül kaldıraç yakalanmamış istisnalar halinde var mı?

Bana node.js içinde yakalanmamış istisnalar işlemek için ortak en iyi uygulamaları gösterecek bir işaretçi/makale seviniriz

CEVAP
5 EYLÜL 2011, PAZARTESİ


Güncelleme: şimdi their own guide this answer belirtilen Joyent. Aşağıdaki bilgiler bir özet daha

"Atma" hataları . güvenle

İdeal istiyoruz önlemek için yakalanmamış hataları mümkün olduğunca, gibi, yerine kelimenin tam anlamıyla atma hata yapabiliriz yerine güvenli bir şekilde "atmak" hata birini kullanarak aşağıdaki genel olarak, bizim kod mimarisi:

  • Eğer bir hata olursa, zaman uyumlu kod, hata döndürür:

    // Define divider as a syncrhonous function
    var divideSync = function(x,y) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by returning it
            return new Error("Can't divide by zero")
        }
        else {
            // no error occured, continue on
            return x/y
        }
    }
    
    // Divide 4/2
    var result = divideSync(4,2)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/2=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/2=' result)
    }
    
    // Divide 4/0
    result = divideSync(4,0)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/0=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/0=' result)
    }
    
  • Geri arama tabanlı (yani. asenkron) kodu, ilk tartışmanın geri arama err, eğer bir hata olur err hata, hata olmaz o zaman err null. Diğer değişkenler err değişken izleyin:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    divide(4,2,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/2=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/2=' result)
        }
    })
    
    divide(4,0,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/0=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/0=' result)
        }
    })
    
  • Hata her yerde hata atmak yerine ortaya çıkabilir eventful kod error event instead yangın çıktı

    // Definite our Divider Event Emitter
    var events = require('events')
    var Divider = function(){
        events.EventEmitter.call(this)
    }
    require('util').inherits(Divider, events.EventEmitter)
    
    // Add the divide function
    Divider.prototype.divide = function(x,y){
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by emitting it
            var err = new Error("Can't divide by zero")
            this.emit('error', err)
        }
        else {
            // no error occured, continue on
            this.emit('divided', x, y, x/y)
        }
    
        // Chain
        return this;
    }
    
    // Create our divider and listen for errors
    var divider = new Divider()
    divider.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    divider.on('divided', function(x,y,result){
        console.log(x '/' y '=' result)
    })
    
    // Divide
    divider.divide(4,2).divide(4,0)
    

"Alıcı" hataları . güvenle

Bazen olsa da, yine de eğer güvenli bir şekilde yakalamak bizde ise hiç yakalanmamış bir istisna ve bizim uygulama potansiyel çökmesine neden olabilir bir yerlerde bir hata atar bu kod da olabilir. Aşağıdaki yöntemlerden birini yakalamak için kullanabileceğimiz kod bizim mimarlık bağlı:

  • Hatanın nerede oluştuğunu bilirsek, node.js domain Bu bölümde kaydırma yapabiliriz

    var d = require('domain').create()
    d.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    
    // catch the uncaught errors in this asynchronous or synchronous code block
    d.run(function(){
        // the asynchronous or synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    })
    
  • Eğer hatanın nerede oluştuğunu bilirsek senkron kod ve etki alanları (düğüm belki eski sürüm) kullanamıyorum ne olursa olsun, catch deyimi kullanabiliriz:

    // catch the uncaught errors in this synchronous code block
    // try catch statements only work on synchronous code
    try {
        // the synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    } catch (err) {
        // handle the error safely
        console.log(err)
    }
    

    Ancak, zaman uyumsuz olarak atılmış bir hata yakaladı olmayacak gibi zaman uyumsuz kod try...catch kullanmak için dikkatli olun:

    try {
        setTimeout(function(){
            var err = new Error('example')
            throw err
        }, 1000)
    }
    catch (err) {
        // Example error won't be caught here... crashing our app
        // hence the need for domains
    }
    

    try...catch ile ilgili dikkatli olmak başka bir şey gibi try deyimi içinde tamamlama geri sarma riski vardır:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    var continueElsewhere = function(err, result){
            throw new Error('elsewhere has failed')
    }
    
    try {
            divide(4, 2, continueElsewhere)
            // ^ the execution of divide, and the execution of 
            //   continueElsewhere will be inside the try statement
    }
    catch (err) {
            console.log(err.stack)
            // ^ will output the "unexpected" result of: elsewhere has failed
    }
    

    Bu yakaladım kodunuzu daha karmaşık hale geldikçe yapmak çok kolaydır. Gibi, iyi ya da etki alanları kullanın veya hataları (1) zaman uyumsuz kod yakalanmamış özel durumları önlemek için return (2) deneyin yakalamak için istemediğiniz yürütme yakalamak için. JavaScript yerine uygun bir iş parçacığı için izin diller olay-makine tarzı, zaman uyumsuz olarak, bu sorunu daha az.

  • Son olarak, durumda bir yakalanmamış hata olur bir yer değildi sarılı bir etki alanı veya bir catch deyimi, biz yapmak bizim uygulama çökme kullanarak uncaughtException dinleyici (ancak bunu yaparken can koymak uygulama unknown state):

    // catch the uncaught errors that weren't wrapped in a domain or try catch statement
    // do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
    process.on('uncaughtException', function(err) {
        // handle the error safely
        console.log(err)
    })
    
    // the asynchronous or synchronous code that emits the otherwise uncaught error
    var err = new Error('example')
    throw err
    

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • itfigueres

    itfigueres

    12 EKİM 2013
  • joshsnice

    joshsnice

    28 Kasım 2006
  • The Bad Tutorials

    The Bad Tuto

    6 EKİM 2009