如何处理Plack延迟响应中的错误

时间:2019-07-05 14:14:16

标签: perl plack

试图处理延迟响应中的错误。

每次发送[200,['Content-Type','application / json'] 并在冲洗其他类似内容之前出错

$ w-> write(“ MyData”);

$ w-> close();

我在stdout中收到了警告,在stderr中出现了错误,但是页面一直在加载。

它将一直加载,直到我停止手动停止应用程序或页面加载。

在使用延迟响应的应用中,如何停止在代码中加载页面?如何正确处理错误?

Perl版本5.24 海带版1.02 与电晕一起运行Plack。

我们正在处理引发Exception :: Class的错误。 使用Try :: Tiny捕获错误。

也尝试使用eval和其他方法,但不起作用。 但是更改了Try :: Tiny-> TryCatc并返回,如果有任何错误,但是 我需要为每个catch块写回信,它看起来非常糟糕

#!/usr/bin/perl
use strict;
use warnings;

use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;
        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $data = 10 / 0;
        $w->write("MyData");
        $w->close();
    }
};
run;

我正在寻找正确的错误处理方式, 我需要尝试{}赶上{}吗?在每个可能失败的代码上?

感谢@ikegami的回答,但是在尝试使用Object :: Destoyer和Sub :: ScopeFinalizer后,页面仍在加载。据我了解$ w(writer)不会导致页面加载。退出范围后,$ w变为undef,那么没有什么可关闭的,这里是代码。

#!/usr/bin/perl
use strict;
use warnings;

use Object::Destroyer;
use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;

        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $g = Object::Destroyer->new( sub { $w->close if $w } );
        my $zzz = 1 / 0;
        $w->write("DATA");
        $w->close();
    }
};
run;

所以我想出了这个解决方案,您怎么看?

#!/usr/bin/perl
use strict;
use warnings;

use Try::Tiny;
use Object::Destroyer;
use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;

        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $g = Object::Destroyer->new( sub { $w->close if $w; } );
        my $ans = try {                                                                   
            my $zzz = 1 / 0;                                                              
        }                                                                                 
        catch {
            print $_;                                                                   
            return;                                                                       
        };                                                                                
        return unless $ans;

        $w->write("DATA");
        $w->close();
    }
};
run;

1 个答案:

答案 0 :(得分:1)

通过包装应用程序解决此问题

Plack::Middleware::HTTPExceptions