【发布时间】:2018-12-21 11:40:15
【问题描述】:
在 ruby 中,您可以像这样重新定义多个异常:
begin
...
rescue Exception1, Exception2
...
rescue Exception1
...
rescue Exception2
...
end
但我不知道如何引发多个异常:
1] pry(main)> ? raise
From: eval.c (C Method):
Owner: Kernel
Visibility: private
Signature: raise(*arg1)
Number of lines: 13
With no arguments, raises the exception in $! or raises
a RuntimeError if $! is nil.
With a single String argument, raises a
RuntimeError with the string as a message. Otherwise,
the first parameter should be the name of an Exception
class (or an object that returns an Exception object when sent
an exception message). The optional second parameter sets the
message associated with the exception, and the third parameter is an
array of callback information. Exceptions are caught by the
rescue clause of begin...end blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
或者我无法在raise doc中找到这个
这样做的目的是我有一个 API 调用,这个调用试图在 API 中创建一个对象。 然后 APi 可以从 Activerecord Validators 返回对象中的所有问题,所以我可以得到这样的想法,例如:
422 "The Item is not even","The Item 需要大于 100" 第422章 200 OK “项目已创建” 500“我是个发球台
我们的想法是捕获这个并引发这样的异常
Begin
API CALL
rescue ItemnotEven,ItemnotBigger
do something
retry if
rescue ItemnotEven
retry if
rescue Connection error
Log cannot connect
end
【问题讨论】:
-
引发多个异常的目的是什么?
-
通过引发多个异常甚至不清楚您的意思。当您说可以挽救多个异常时,它们不会同时保存;你可以一次养一只。
-
目的是我可以得到一个对象构造的多次失败,所以每次失败我都会抛出一个异常
-
引发多个异常甚至没有意义,而且我个人不知道有任何语言可以实现这样的事情。有诸如内部异常之类的事情,其中一个导致另一个,但没有引发它们....
标签: ruby validation exception exception-handling