Commit Graph

93 Commits

Author SHA1 Message Date
Maxime Lapointe
3e816bfe72 Fixes tests with nested exception backtraces on Ruby master
Ruby master did the following changes (and probably more)
https://bugs.ruby-lang.org/issues/16495
https://bugs.ruby-lang.org/issues/20275
2024-06-17 09:43:28 -04:00
Maxime Lapointe
f47ef36c4d
Log trace of causes for unhandled exceptions 2024-06-12 22:51:15 +00:00
Jean Boussier
50daadaa71 Update test suite for compatibility with Ruby 3.4-dev
https://bugs.ruby-lang.org/issues/19117 and https://bugs.ruby-lang.org/issues/16495
slightly change how backtrace are rendered which makes a few tests fail.
2024-02-16 11:55:44 +01:00
fatkodima
4fc2df277d Include exception causes into log messages 2023-11-23 17:21:28 +02:00
Akhil G Krishnan
7df276f938 Add Rack::Lint to DebugExceptions missing test 2023-07-31 13:19:32 +05:30
Hartley McGuire
ac7ee278fd
Add Rack::Lint to DebugExceptions tests
This adds additional test coverage to DebugExceptions to validate that
its behavior conforms to the Rack SPEC.

The only changes necessary were to use dynamic header casing for
Content-Type and Content-Length
2023-07-29 16:49:10 -04:00
Adrianna Chang
2401b336fb
Use expected casing for x-cascade headers in router
This commit changes the router to use the expected casing for the
x-cascade header: in Rack 2, this is mixed-case, and in Rack 3, this is
lower case.

This also fixes https://github.com/rails/rails/issues/47096.
2023-07-28 16:17:08 -04:00
Hartley McGuire
519577ecc3
Make the log level in DebugExceptions configurable
This middleware has been logging at a FATAL level since the first
[commit][1] in Rails (the code originally lived in
actionpack/lib/action_controller/rescue.rb). However, FATAL is
documented in the Ruby Logger [docs][2] as being for "An unhandleable
error that results in a program crash.", which does not really apply to
this case since DebugExceptions is handling the error. A more
appropriate level would be ERROR, which the Ruby Logger docs describe as
"A handleable error condition."

This commit introduces a new configuration for the DebugExceptions log
level so that new apps will have it set to ERROR by default and ERROR
can eventually be made the default.

[1]: db045dbbf60b53dbe013ef25554fd013baf88134
[2]: https://ruby-doc.org/3.2.1/stdlibs/logger/Logger/Severity.html
2023-06-25 23:11:39 -04:00
Jon Dufresne
e28f147329 Make the test environment show rescuable exceptions in responses
Background
----------

During integration tests, it is desirable for the application to respond
as closely as possible to the way it would in production. This improves
confidence that the application behavior acts as it should.

In Rails tests, one major mismatch between the test and production
environments is that exceptions raised during an HTTP request (e.g.
`ActiveRecord::RecordNotFound`) are re-raised within the test rather
than rescued and then converted to a 404 response.

Setting `config.action_dispatch.show_exceptions` to `true` will make the
test environment act like production, however, when an unexpected
internal server error occurs, the test will be left with a opaque 500
response rather than presenting a useful stack trace. This makes
debugging more difficult.

This leaves the developer with choosing between higher quality
integration tests or an improved debugging experience on a failure.

I propose that we can achieve both.

Solution
--------

Change the configuration option `config.action_dispatch.show_exceptions`
from a boolean to one of 3 values: `:all`, `:rescuable`, `:none`. The
values `:all` and `:none` behaves the same as the previous `true` and
`false` respectively. What was previously `true` (now `:all`) continues
to be the default for non-test environments.

The new `:rescuable` value is the new default for the test environment.
It will show exceptions in the response only for rescuable exceptions as
defined by `ActionDispatch::ExceptionWrapper.rescue_responses`. In the
event of an unexpected internal server error, the exception that caused
the error will still be raised within the test so as to provide a useful
stack trace and a good debugging experience.
2023-05-17 06:30:28 -07:00
John Bampton
2f699c51ce Fix word case. html -> HTML 2022-09-18 04:21:22 +10:00
Eugene Kenny
d6b66ebb6e Pass log_rescued_responses as environment config
This lets us remove the reference to DebugExceptions from the Action
Dispatch railtie, which was causing load order issues since it depends
on ActionDispatch::Request.
2021-07-19 00:08:30 +01:00
Petrik
0409ed57ac Clean up checks to see if DidYouMean is defined
As of Ruby 2.7 DidYouMean is included as a default gem, so there is no
need to check if DidYouMean is defined in the test suite. We still need
to check if the DidYouMean modules are defined in the actual code, as
someone might run Rails with DidYouMean disabled by using the
`--disable-did_you_mean` flag. This is ussually done for performance
reasons.

This commit also includes some of the changes made by Yuki in:
https://github.com/rails/rails/pull/39555
These changes include replacing Jaro with the more accurate
SpellChecker, and using DidYouMean::Correctable for simplere
corrections.

The DidYouMean::SpellChecker does have a treshold for corrections.
If there is not enough similarity it might not return a suggestion.
To stop the tests from failing some test data had to be changed.

For example, `non_existent` does not meet the treshold for `hello`, but
`ello` does:

DidYouMean::SpellChecker.new(dictionary: %w[hello]).correct('non_existent')
=> []
DidYouMean::SpellChecker.new(dictionary: %w[hello]).correct('ello')
=> ["hello"]

The treshold makes sense for spelling errors. But maybe we should add a
different SpellChecker that helps to get a suggestion even if there is
little overlap. For example for when a model only has 2 attributes
(title and body), it's helpful to get a suggestion for `name`

Co-Authored-By: Yuki Nishijima <yk.nishijima@gmail.com>
2021-07-04 13:43:50 +02:00
Alexander Azarov
dc2d948930
Skip logging backtrace when exception is in rescue_responses
Closes #9343

Co-authored-by: Mike Dalessio <mike.dalessio@gmail.com>
2021-06-24 23:04:12 -04:00
Ashik Salman
b37b90251f Return an empty array if annotated_source_code is nil. 2021-05-05 23:29:23 +05:30
Haroon Ahmed
93f0cebd1d Display exception messages using simple_format for a better and clearer
exception message.
2020-11-09 21:48:24 +00:00
Rafael Mendonça França
f2caed1e73
Don't log backtrace for ActionDispatch::Http::MimeNegotiation::InvalidType 2020-10-07 17:30:07 +00:00
Jonathan Rochkind
2bad7eb111 Raise more specific exception for invalid mime type from user-agent
To be able to distinguish from other kinds of `Mime::Type::InvalidMimeType` that may be raised by user or third-party code. It's only failure in parsing client-supplied content-types in ActionDispatch::Http::MimeNegotiation that should result in special handling.

This also allows third-party error handling/tracking code to specifically target the new `ActionDispatch::Http::MimeNegotiation::InvalidType` for ignoring or other special handling, separate from  `Mime::Type::InvalidMimeType`

This is a revision of #35753 in response to #37620 and discussion with @eugeneius
2020-10-07 11:49:56 -04:00
Rafael Mendonça França
d98d749222
Revert "Merge pull request #39304 from zenspider/zenspider/backtrace_filter_should_never_return_empty"
This reverts commit 2eb7aa111bbbf69fe89bdcd96b4839480e2ac076, reversing
changes made to 0b28f0c39c5b0a0009f1ea9d13ce97704e20c85b.

Rails backtrace cleaner needs to be able to return empty traces to
separate application code from the framework code and not report
exceptions that happen inside only framework code.

See
345de17caf/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb (L72).
2020-10-06 22:31:41 +00:00
Rafael França
91cd8ccdb5
Merge pull request #39363 from p8/format-did-you-mean-suggestions-on-error-pages
Use html for DidYouMean suggestions on error pages
2020-08-26 16:15:36 -04:00
Eugene Kenny
57daae230b Assert that DebugExceptions renders HTML by default
This would have made the correct implementation for
894ed87a7e0e1ba36b8ba8f8ead0a871550354e5 more obvious.
2020-07-20 22:37:35 +01:00
Loren Norman
894ed87a7e Fix InvalidMimeType errors not being caught, with tests.
Co-authored-by: Eugene Kenny <elkenny@gmail.com>
2020-07-20 11:45:57 -04:00
Petrik
5cf725acb6 Use html for DidYouMean suggestions on error pages
The current suggestions are shown on a single line.
Instead we can use some prettier formatting.
2020-05-22 18:33:55 +02:00
Ryan Davis
39e8cab17a Fixes against the previous commit.
Happy to squash this before merge. Just separate so I can whittle
these down.

Most of the problem seems to be centered around the backtrace filter
being both for general use and for minitest... and I'm only aware of /
addressing minitest issues.

If they really need to be separate, then we can make a separate one
for minitest.
2020-05-15 16:42:27 -07:00
Eugene Kenny
d7b015a167 Encode template source before extracting lines
Before 2169bd3d2a9d2f331a5dd6e41d9d638e0da6117c, a template's source was
encoded in place when it was compiled, and the `source_extract` method
could rely on `Template#source` to return a properly encoded string.

Now that `Template#source` always returns a new copy of the template
source with no encoding, `source_extract` should call `encode!` itself.
2019-12-21 07:30:52 +00:00
Genadi Samokovarov
7465b383ea
Fix DebugExceptions crash on nil Exception#annoted_source_code
The issue was reported in #29537. We expect Exception#annoted_source_code
to return an `Array`, but this contract may not be followed by all the
implementers.

Fixes #29537.
2019-12-19 12:43:08 -03:00
Akira Matsuda
d1ffe59ab5 Use match? where we don't need MatchData
We're already running Performance/RegexpMatch cop, but it seems like the cop is not always =~ justice
2019-07-27 13:06:49 +09:00
Rafael Mendonça França
a115a4cc79
Merge pull request #31634 from afcapel/reduce-routing-error-log-noise
Reduce log noise handling ActionController::RoutingErrors
2019-07-16 14:16:28 +01:00
yuuji.yaginuma
ea5f509643 Change ActionDispatch::Response#content_type returning Content-Type header as it is
Since #35709, `Response#conten_type` returns only MIME type correctly.
It is a documented behavior that this method only returns MIME type, so
this change seems appropriate.
39de7fac05/actionpack/lib/action_dispatch/http/response.rb (L245-L249)

But unfortunately, some users expect this method to return all
Content-Type that does not contain charset. This seems to be breaking
changes.

We can change this behavior with the deprecate cycle.
But, in that case, a method needs that include Content-Type with
additional parameters. And that method name is probably the
`content_type` seems to properly.

So I changed the new behavior to more appropriate `media_type` method.
And `Response#content_type` changed (as the method name) to return Content-Type
header as it is.

Fixes #35709.

[Rafael Mendonça França & Yuuji Yaginuma ]
2019-06-01 09:20:13 +09:00
Alberto Fernández Capel
c8f4c53d55 Reduce log noise handling ActionController::RoutingErrors
Each time a missing route is hit 32 lines of internal rails traces
are written to the log. This is overly verbose and doesn't offer
any actionable information to the user.

With this change we'll still write an error message showing the
route error but the trace will be omitted.
2019-05-28 20:39:10 +01:00
Eileen M. Uchitelle
d155f61b64 Merge pull request #36196 from st0012/fix-29947
Hide malformed parameters from error page

Accidentally merged this to 6-0-stable so forward porting it to master
here instead.
2019-05-07 15:14:14 -04:00
Genadi Samokovarov
a3110fe20b Drop the ambiguous ActiveSupport::ActionableError#=== check 2019-04-19 14:15:22 +09:00
Sharang Dashputre
249622e748 url -> URL where apt inside actionpack/ 2019-04-01 22:58:02 +05:30
Edouard CHIN
378b4fedb1 Add the Mime::Type::InvalidMimeType error in the default rescue_response:
- https://github.com/rails/rails/pull/35604 introduced a vulnerability fix
  to raise an error in case the `HTTP_ACCEPT` headers contains malformated
  mime type.

  This will cause applications to throw a 500 if a User Agent sends an
  invalid header.

  This PR adds the `InvalidMimeType` in the default `rescue_responses` from
  the ExceptionWrapper and will return a 406. I looked up the HTTP/1.1
  RFC and it doesn't stand what should be returned when the UA
  sends malformated mime type. Decided to get 406 as it seemed to be the
  status the better suited for this.
2019-03-26 02:03:47 +01:00
Aaron Patterson
d4015a7f06
Pass locals in to the template object on construction
This commit ensures that locals are passed in to the template objects
when they are constructed, then removes the `locals=` mutator on the
template object.  This means we don't need to mutate Template objects
with locals in the `decorate` method.
2019-02-25 15:14:53 -08:00
Aaron Patterson
2f128a82e6
Always pass a format to the ActionView::Template constructor
This means we can eliminate nil checks and remove some mutations from
the `decorate` method.
2019-02-25 12:26:25 -08:00
yuuji.yaginuma
7a1254cdb5 Loosen check of error cause file
Since "actionpack" is not included in isolation test.
Ref: https://travis-ci.org/rails/rails/jobs/484514392#L2715
2019-01-26 10:13:47 +09:00
Yuki Nishijima
ef40fb6fd8 Fixed a bug where the debug view does not show the error page properly
There are two cases where the debug view does not show the error details
properly:

 * When the cause is mapped to an HTTP status code the last exception is
   unexpectedly uwrapped
 * When the last error is thrown from a view template the debug view is
   not using the `rescues/template_error.html.erb` to generate the view

Both the cases could be fixed by not unwrapping the exception. The only
case where the exception should be unwrapped is when the last error is
an `ActionView::Template::Error` object. In this case the HTTP status
code is determined based on the cause.

There are actually more wrapper exceptions that are intentionally
thrown. However, there is a consistent pattern of setting the original
message and original backtrace to the wrapper exception implemented, so
the debug view will not lose the information about what went wrong
eariler.
2019-01-24 20:30:20 -05:00
Yuki Nishijima
6922ba6cb6 Prefer strings over regex expressions
In this case statement, there are two patterns that start with the same
line:

  when %r{/not_found}
    ...
  when %r{/not_found_original_exception}
    ...

Because the string "/not_found_original_exception" does match the first
one, it is never routed to what it is supposed to be routed, causing one
of the tests for DebugExceptions to happen to be passing.

After changing the regex expressions back to strings, I noticed that the
test setup is not complete (the template object needs to be a proper
template object). Once I fixed it all the tests started padding.
2019-01-24 15:49:05 -05:00
alkesh26
78cf58b765 1. Replaced unused variables by _.
2. Typo fixes.
2019-01-22 22:27:01 +05:30
Ryuta Kamizono
892e38c78e Enable Style/RedundantBegin cop to avoid newly adding redundant begin block
Currently we sometimes find a redundant begin block in code review
(e.g. https://github.com/rails/rails/pull/33604#discussion_r209784205).

I'd like to enable `Style/RedundantBegin` cop to avoid that, since
rescue/else/ensure are allowed inside do/end blocks in Ruby 2.5
(https://bugs.ruby-lang.org/issues/12906), so we'd probably meets with
that situation than before.
2018-12-21 06:12:42 +09:00
yuuji.yaginuma
1b86d90136 Enable Performance/UnfreezeString cop
In Ruby 2.3 or later, `String#+@` is available and `+@` is faster than `dup`.

```ruby
# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "benchmark-ips"
end

Benchmark.ips do |x|
  x.report('+@') { +"" }
  x.report('dup') { "".dup }
  x.compare!
end
```

```
$ ruby -v benchmark.rb
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
Warming up --------------------------------------
                  +@   282.289k i/100ms
                 dup   187.638k i/100ms
Calculating -------------------------------------
                  +@      6.775M (± 3.6%) i/s -     33.875M in   5.006253s
                 dup      3.320M (± 2.2%) i/s -     16.700M in   5.032125s

Comparison:
                  +@:  6775299.3 i/s
                 dup:  3320400.7 i/s - 2.04x  slower

```
2018-09-23 08:56:55 +09:00
Yuki Nishijima
1f525b4f7d Show nested exceptions on the debug view 2018-07-15 20:54:19 -04:00
Genadi Samokovarov
d25fba89d4 Introduce ActionDispatch::DebugExceptions interceptors
Plugins interacting with the exceptions caught and displayed by
ActionDispatch::DebugExceptions currently have to monkey patch it to get
the much needed exception for their calculation.

With DebugExceptions.register_interceptor, plugin authors can hook into
DebugExceptions and process the exception, before being rendered. They
can store it into the request and process it on the way back of the
middleware chain execution or act on it straight in the interceptor.

The interceptors can be play blocks, procs, lambdas or any object that
responds to `#call`.
2018-04-20 14:55:37 +03:00
Koichi ITO
d2901bd517 [Action Pack] rubocop -a --only Layout/EmptyLineAfterMagicComment 2017-07-11 13:12:32 +09:00
Kir Shatrov
b3f3d49fd6 Prepare AP and AR to be frozen string friendly 2017-07-06 21:30:43 +03:00
Matthew Draper
87b3e226d6 Revert "Merge pull request #29540 from kirs/rubocop-frozen-string"
This reverts commit 3420a14590c0e6915d8b6c242887f74adb4120f9, reversing
changes made to afb66a5a598ce4ac74ad84b125a5abf046dcf5aa.
2017-07-02 02:15:17 +09:30
Kir Shatrov
cfade1ec7e Enforce frozen string in Rubocop 2017-07-01 02:11:03 +03:00
Rafael Mendonça França
fe1f4b2ad5
Add more rubocop rules about whitespaces 2016-10-29 01:17:49 -02:00
Genadi Samokovarov
f99c37583d Support plain loggers in DebugExceptions
I have been seeing people setting `Logger` instances for `config.logger`
and it blowing up on `rails/web-console` usage.

Now, I doubt many folks are manually setting `ActionView::Base.logger`,
but given that `DebugExceptions` is running in a pretty fragile
environment already, having it crash (and being silent) in those cases
can be pretty tricky to trace down.

I'm proposing we verify whether the `ActionView::Base.logger` supports
silencing before we try to do it, to save us the headache of tracing it
down.
2016-10-28 23:53:06 +03:00
Rafael Mendonça França
55f9b8129a
Add three new rubocop rules
Style/SpaceBeforeBlockBraces
Style/SpaceInsideBlockBraces
Style/SpaceInsideHashLiteralBraces

Fix all violations in the repository.
2016-08-16 04:30:11 -03:00