feat(common): allow passing errorCode in HttpExceptionOptions#15525
feat(common): allow passing errorCode in HttpExceptionOptions#15525lhj0621 wants to merge 1 commit intonestjs:masterfrom
Conversation
Pull Request Test Coverage Report for Build 0b78bf17-bf06-43d6-95c7-979d7875201aDetails
💛 - Coveralls |
|
Why don't you create a dedicated exception class in your project instead? For instance, |
Hi, thank you for the insightful feedback! That's a very valid point. // Boilerplate code in the user's project
class AppHttpException extends HttpException {
constructor(message: string, status: number, public readonly errorCode: string) {
super({ message, errorCode, statusCode: status, error: 'Bad Request' }, status);
}
}
// And use it like this:
throw new AppHttpException('Password is too short', 400, 'PASSWORD_TOO_SHORT');With this PR: // Cleaner, framework-supported way
throw new BadRequestException('Password is too short', {
errorCode: 'PASSWORD_TOO_SHORT'
});By integrating this small, non-breaking feature directly into the framework, we empower all NestJS developers with a cleaner, more robust way to implement this best practice. It enhances the framework itself for building large-scale APIs where structured error handling is crucial. |
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Currently,
HttpExceptionprovides astatusand amessageto describe an error. While this is effective for general error reporting, it lacks a mechanism for conveying a specific, machine-readable error cause.For example, multiple validation failures (e.g., invalid email, weak password) might all result in a
400 Bad Request. Without a distinct error code, client applications are forced to parse the human-readable error message string to determine the specific cause, which is brittle and unreliable.Issue Number: N/A
What is the new behavior?
This PR introduces a new optional
errorCodeproperty toHttpExceptionOptions. This allows developers to attach a specific, machine-readable error code to an exception.This
errorCodeis then included in the JSON response body, enabling clients to programmatically and reliably handle different error scenarios without parsing fragile message strings.Example Usage:
Example Response:
{ "statusCode": 400, "message": "The password is too short.", "error": "Bad Request", "errorCode": "PASSWORD_TOO_SHORT" }Does this PR introduce a breaking change?
This change is fully non-breaking as the
errorCodeproperty is optional and does not affect any existing functionality.Other information
This feature enhances NestJS's capabilities for building mature, large-scale applications by aligning it with common API design best practices.