我正在尝试找出在mod_perl 2下完成响应而不返回主处理程序的方法。到目前为止,还没有在文档中找到这方面的方法。以下是我要实现的示例:
#!/usr/bin/perl
# This is some mod_perl handler
use strict;
use warnings;
use Apache2::Const ':common';
sub handler {
my $r = shift;
if ($r->method eq 'POST') {
# just to do something as example
do_post_response($r);
}
$r->content_type('text/plain');
print "Thank you, goodbye.";
return Apache2::Const::OK;
}
sub do_post_response {
my $r = shift;
unless (check_somthing()) {
# Suppose I find a situation that requires
# a different response than normal...
$r->content_type('text/plain');
print "We have a situation...";
$r->something_to_finish_the_request_immediatly(Apache2::Const::OK);
}
}
在普通的Perl脚本中,作为独立运行或在mod_cgi下运行,我可以使用 exit() 带着新的响应退出,但在 mod_perl 中,我需要在原始的 handler 子程序中返回一些内容。这导致我需要跟踪整个调用链,其中所有调用都必须返回一些内容,直到回到主要的 handler 。unless (check_something()) { ...
我需要做像这样的事情:
my $check = check_something();
return $check if $check;
我还必须在主处理程序中做类似的事情,这对于某些情况处理来说非常丑陋。
有没有一种方法可以在嵌套调用中关闭请求,就像我尝试用示例说明的那样?
编辑:我发现我可以调用 goto LABEL
并将该标签放置在主handler
子例程中的最后一个return之前。 它起作用,但仍然感觉像一个肮脏的黑客。 我真的希望有更好的方法。
die "We have a situation...";
,并在handler()中使用eval
块或更好地使用类似于Try::Tiny
的模块进行捕获。如果需要区分自定义异常和其他可能由未捕获的故障引起的异常,请添加一些Exception::Class
。 - mbethke