Fix blackd returning 500 for invalid f-strings#5074
Conversation
When blackd receives code with invalid f-strings (e.g. f"{}"), ast.parse()
raises ASTSafetyError. This fell through to the generic except Exception
handler, returning HTTP 500. Add specific handler to return HTTP 400.
Fixes #3616
|
This is not correct. ASTSafetyError can indicate a bug in Black, which should be a 500. The linked issue appears to be a case where Black's parser is more lenient than Before you do this make sure you understand what each use of ASTSafetyError in Black is for and what it indicates. |
|
Thanks for the review @JelleZijlstra, and you're absolutely right. I took the time to study all the uses of
My original PR incorrectly treats ALL of these as 400, which is wrong for cases 2 and 3. I agree with your suggestion to split the source-parse-failure case into its own exception. I'll prepare a new version that:
Let me know if you'd prefer a different name for the new exception, or if you'd like a different approach entirely. Happy to implement whichever direction you prefer. |
…yError Per review feedback from @JelleZijlstra: - Source AST parse failure → SourceASTParseError → 400 (user input issue) - Dest AST parse failure / src≠dest → ASTSafetyError → 500 (Black bug) - New SourceASTParseError exception in parsing.py for source parse case - blackd catches SourceASTParseError separately for correct HTTP status
- Add SourceASTParseError exception for source file AST parse failures (user input issue, not a Black bug) - Keep ASTSafetyError for Black output issues (invalid code, non-equivalent) - In blackd, return 400 for SourceASTParseError, 500 for ASTSafetyError - Per @JelleZijlstra review feedback on psf#5074
Problem
When
blackdreceives code with invalid f-strings (e.g.f"{}"),ast.parse()raisesASTSafetyError. This falls through to the genericexcept Exceptionhandler, returning HTTP 500 (Internal Server Error).It should return HTTP 400 (Bad Request), consistent with how
InvalidInputis handled.Solution
Add a specific
except ASTSafetyErrorhandler before the genericexcept Exception, returning HTTP 400.Fixes #3616