如何在Rails中捕获500个内部服务器错误 [英] How to catch a 500 Internal Server Error in Rails

查看:66
本文介绍了如何在Rails中捕获500个内部服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从数据库等中获取内容之前,我已经做过无数次了.

I have done this tons of times before when fetching things from a database, etc.

对于我的特定情况,我正在使用第三方连接到硬件...无论如何,如果出现错误,例如无效的ID ,显然,我们想引发异常或抢救...但不幸的是,我不知道如何提高它,因为到它被击中时,为时已晚(我认为)

For my specific case I am using a 3rd party to connect to a piece of hardware... Anyways, in the case of an error, such as an invalid id obviously, we want to raise a exception or a rescue... but unfortunately I don't know how to raise it because by the time it is hit, it's too late (I think)

这里...

# 
# getting params and saving item above...
# 

if item.save
  device = RubySpark::Device.new("FAKEUNITID800")
  device.function("req", "ITEM")
  redirect_to controller: 'items', action: 'edit_items'
end

如果这是一个有效的ID,则一切正常,它将带您进入/edit页面!但是问题是,使用无效的ID,它确实可以...

If this was a valid ID, everything would work, and it would take you to the /edit page! But the issue is, with an invalid ID, it just does...

Completed 500 Internal Server Error in 897ms

RubySpark::Device::ApiError - Permission Denied: Invalid Device ID:

我查看了以下教程

  • Rescue StandardError, Not Exception
  • How to catch 404 and 500 error in Rails?
  • Dynamic Rails Error Pages

但是说实话,它们只是让我更加困惑.也许我对此有错误的做法.我一直以为,首先您发出请求,然后又遇到一个后备案例,具体取决于您所处的状态(例如200、500、404)...从那里去.

But honestly, they just make me more confused. Maybe I have the wrong approach to this. I always thought that first you make the request, and then you have a fall back case, depending what status (ie. 200, 500, 404) you get... you go from there.

推荐答案

Rails返回500 Internal Server Error响应,因为引发了一个异常,说明该异常不会如何处理.您不能在Rails中挽救"500 Internal Server Error",因为它不是一个例外-它是从未捕获的异常中解脱出来的框架,以避免数据丢失或不可预测的行为.

Rails returns an 500 Internal Server Error response because an exception was raised that it does not no how to handle. You can't rescue "500 Internal Server Error" in Rails because it is not an exception - its the framework bailing from an uncaught exception to avoid data loss or unpredictable behavior.

幸运的是,您不必这样做.您可以挽救RubySpark异常:

Fortunatly you don't have to. You can just rescue the RubySpark exception:

begin
  device = RubySpark::Device.new("FAKEUNITID800")
  device.function("req", "ITEM")
rescue RubySpark::Device::ApiError => e
  logger.error(e.message)
end

您还可以在Rails控制器中使用 rescue_from 将整个操作包装在before块中:

You can also use rescue_from in Rails controllers that wraps the entire action in a before block:

class FooController < ApplicationCotnroller
  rescue_from RubySpark::Device::ApiError, with: :do_something
  # ...
end

这篇关于如何在Rails中捕获500个内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆