提问人:N0ne 提问时间:11/23/2022 更新时间:11/23/2022 访问量:64
我应该在哪里以及如何处理多个异常?
Where and how should I handle multiple exceptions?
问:
我在处理异常时遇到了问题。我知道该怎么做,但我不确定什么是营救他们的正确地方。例如:
class ExampleService
def call
...
raise ExampleServiceError, 'ExampleService message'
end
end
class SecondExampleService
def call
raise SecondExampleServiceError if something
ExampleService.call
rescue ExampleService::ExampleServiceError => e ---> should I rescue it here?
raise SecondExampleServiceError, e.message
end
end
Class ExampleController
def update
SecondExampleService.call
rescue ExampleService::ExampleServiceError, SecondExampleService::SecondExampleServiceError => e
render json: { error: e.message }
end
end
正如您在示例中看到的,我有两个服务。 提出了他自己的例外。 调用 ,可以引发异常,并在 中使用。我应该在哪里救援?在 或 ?如果在 ,当我们在多个控制器中使用这样的服务时(救援代码会重复很多次)呢?ExampleService
SecondExampleService
ExampleService
ExampleController
ExampleServiceError
ExampleController
SecondExampleService
ExampleController
答:
3赞
spickermann
11/23/2022
#1
当控制器只直接调用并且对 一无所知时,它不应该从 中救援。SecondExampleService
ExampleService
ExampleServiceError
只知道它是在内部使用的,因此应该从中拯救并翻译成 .SecondExampleService
ExampleService
SecondExampleService
ExampleServiceError
SecondExampleServiceError
这就是我对得墨忒耳定律的解释。
评论