backend-error 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +68 -57
  2. package/package.json +15 -10
package/README.md CHANGED
@@ -1,37 +1,58 @@
1
- # Backend-error
1
+ # backend-error
2
2
 
3
- BackendError is a lightweight utility for structured and user-aware error handling in Node.js backends. It helps distinguish operational errors from unexpected crashes, and supports standardized error responses across services.
3
+ ![npm](https://img.shields.io/npm/v/backend-error)
4
+ ![downloads](https://img.shields.io/npm/dm/backend-error)
5
+ ![license](https://img.shields.io/npm/l/backend-error)
4
6
 
5
- > ⚠️ Note: backend-error is not a middleware it's a flexible utility for throwing and formatting structured errors. It works seamlessly with Express, Cloud Functions, and any other Node.js-based backend environment where you want standardized, user-aware error responses.
7
+ `backend-error` is a lightweight Node.js / TypeScript utility that formats all errors—custom or native—into standardized HTTP responses with correct status codes and user-friendly messages. The `httpErrorFormatter` ensures secure, consistent error output by controlling what is exposed to the frontend.
6
8
 
7
- > 💬 Tip: This package doesn't handle headers or CORS. If you're building an API for browsers, remember to configure CORS separately.
8
-
9
- [![GitHub package.json version (master)](https://img.shields.io/github/package-json/v/eriksturesson/backendError/master)](https://github.com/eriksturesson/backendError)
10
- [![npm](https://img.shields.io/npm/dy/backend-error?label=npm%20downloads)](https://www.npmjs.com/package/backend-error)
9
+ ---
11
10
 
12
- ## Installation
11
+ ## 📦 Installation
13
12
 
14
13
  ```bash
15
14
  npm install backend-error
16
15
  ```
17
16
 
18
- ## 🔥 Custom BackendError class
19
-
20
- Use `BackendError` class for standardized backend error handling:
17
+ ---
21
18
 
22
- ## Usage
19
+ ## 🚀 Throw `BackendError`, catch with `httpErrorFormatter`
23
20
 
24
21
  ```ts
25
- import { BackendError } from "backend-error";
22
+ import { BackendError, httpErrorFormatter } from "backend-error";
26
23
 
27
- throw BackendError.BadRequest("Missing required field");
24
+ app.post("/signup", async (req, res) => {
25
+ try {
26
+ const auth = req.headers.authorization;
27
+ const { email, id } = req.body;
28
+ if (!auth) throw BackendError.Unauthorized("Missing auth token"); // 401, showUser:true
29
+ if (!email) throw BackendError.BadRequest("Email is required"); // 400, showUser:true
30
+ const user = await getUser(req.params.id);
31
+ if (!user) throw BackendError.NotFound("User not found"); // 404, showUser:true
32
+
33
+ // Normal logic...
34
+ } catch (err) {
35
+ const { status, body } = httpErrorFormatter(err); // Handles BackendError and native Error safely
36
+ res.status(status).json(body);
37
+ }
38
+ });
28
39
  ```
29
40
 
30
- Or construct it manually for full control:
41
+ No manual showUser checks handled automatically by the formatter
42
+ ✅ Returns generic 500 for critical or unknown errors (or if `showUser` is false)
43
+ ✅ Formatter supports both BackendError instances and native Error objects
44
+
45
+ > The httpErrorFormatter inspects any error, formats it consistently, and decides what message is safe to show to users.
46
+
47
+ ---
48
+
49
+ ## ✨ Custom BackendError creation
50
+
51
+ If you prefer, create your own error with full control including custom metadata:
31
52
 
32
53
  ```ts
33
54
  const error = new BackendError({
34
- message: "Something went terribly wrong",
55
+ message: "Something went wrong",
35
56
  severity: "critical",
36
57
  showUser: true,
37
58
  code: 500,
@@ -39,35 +60,37 @@ const error = new BackendError({
39
60
  });
40
61
  ```
41
62
 
42
- Properties available:
63
+ ### Selected BackendError options
43
64
 
44
- - `message`: The error message
65
+ - `message`: Error message
45
66
  - `code`: HTTP status code
46
- - `isOperational`: Marks it as a handled error (vs. crash)
47
- - `showUser`: Whether frontend should show the message
67
+ - `showUser`: Whether to expose the message to frontend clients
48
68
  - `severity`: "info" | "warning" | "error" | "critical"
49
- - `data`: Additional metadata (optional and anything accepted)
69
+ - `data`: Optional metadata
50
70
 
51
- ## 🧠 Example where you also import `httpErrorFormatter`:
71
+ ---
72
+
73
+ ## ⚙️ Static error helpers
52
74
 
53
75
  ```ts
54
- import { BackendError, httpErrorFormatter } from "backend-error";
55
- try {
56
- const user = null;
57
- if (!user) throw BackendError.NotFound("User not found");
58
- res.json(user);
59
- } catch (err) {
60
- const { status, body, message, showUser } = await httpErrorFormatter(err);
61
- res.status(status).json(body);
62
- }
76
+ BackendError.BadRequest("..."); // 400, showUser: true
77
+ BackendError.Unauthorized("..."); // 401, showUser: true
78
+ BackendError.Forbidden("..."); // 403, showUser: true
79
+ BackendError.NotFound("..."); // 404, showUser: true
80
+ BackendError.Conflict("..."); // 409, showUser: true
81
+ BackendError.UnprocessableEntity("..."); // 422, showUser: true
82
+ BackendError.Internal("..."); // 500, showUser: false
83
+ BackendError.ServiceUnavailable("..."); // 503, showUser: false
63
84
  ```
64
85
 
65
- ## 🧠 Example of manual showUser handling (done automatically in httpErrorFormatter above)
86
+ ---
87
+
88
+ ## 🧠 Manual error handling (if not using `httpErrorFormatter`)
66
89
 
67
90
  ```ts
68
91
  import { BackendError } from "backend-error";
69
92
 
70
- app.get("/user/:id", async (req, res, next) => {
93
+ app.get("/user/:id", async (req, res) => {
71
94
  try {
72
95
  const user = null;
73
96
  if (!user) throw BackendError.NotFound("User not found");
@@ -82,24 +105,13 @@ app.get("/user/:id", async (req, res, next) => {
82
105
  });
83
106
  ```
84
107
 
85
- ## Available static error constructors
86
-
87
- - `BackendError.BadRequest(message: string)` // 400, showUser: true
88
- - `BackendError.Unauthorized(message: string)` // 401, showUser: true
89
- - `BackendError.Forbidden(message: string)` // 403, showUser: true
90
- - `BackendError.NotFound(message: string)` // 404, showUser: true
91
- - `BackendError.Conflict(message: string)` // 409, showUser: true
92
- - `BackendError.UnprocessableEntity(message: string)`// 422, showUser: true
93
- - `BackendError.Internal(message: string)` // 500, showUser: false
94
- - `BackendError.ServiceUnavailable(message: string)` // 503, showUser: false
108
+ ---
95
109
 
96
110
  ## 🧩 Types
97
111
 
98
112
  ```ts
99
113
  export type Severity = "info" | "warning" | "error" | "critical";
100
- ```
101
114
 
102
- ```ts
103
115
  export interface BackendErrorOptions {
104
116
  message: string;
105
117
  isOperational?: boolean;
@@ -110,29 +122,30 @@ export interface BackendErrorOptions {
110
122
  }
111
123
  ```
112
124
 
125
+ ---
126
+
113
127
  ## 🎨 Works well with [error-drawings](https://www.npmjs.com/package/error-drawings)
114
128
 
115
129
  ![GitHub package.json version (master)](https://img.shields.io/github/package-json/v/eriksturesson/errorDrawings/master)
116
130
  ![npm downloads](https://img.shields.io/npm/dy/error-drawings?label=npm%20downloads)
117
131
 
118
- `npm install error-drawings`
132
+ ```bash
133
+ npm install error-drawings
134
+ ```
119
135
 
120
- If you want fun and visual error output during development, you can combine backend-error with error-drawings. Both libraries support the same severity field ("info" | "warning" | "error" | "critical"), making them plug-and-play together.
136
+ Use for dev-friendly terminal logs with a bit of dramatic flair for critical errors:
121
137
 
122
138
  ```ts
123
- import { BackendError } from "backend-error";
139
+ import { BackendError, httpErrorFormatter } from "backend-error";
124
140
  import drawLog from "error-drawings";
125
141
 
126
142
  try {
127
143
  throw BackendError.Forbidden("No access to resource");
128
144
  } catch (err) {
129
145
  const isCritical = !(err instanceof BackendError && err.isOperational) || err.code >= 500;
130
- if (isCritical) {
131
- // 🔥 Draw dramatic error output to highlight critical issues during development
132
- // 🧠 Important: log BEFORE formatting, since the formatter may hide details if showUser is false
133
- drawLog(err);
134
- }
135
- const { status, body } = await httpErrorFormatter(err); //Use the formatter as always
146
+ if (isCritical) drawLog(err); // Dramatic terminal art for critical errors!
147
+
148
+ const { status, body } = httpErrorFormatter(err);
136
149
  res.status(status).json(body);
137
150
  }
138
151
  ```
@@ -141,8 +154,6 @@ try {
141
154
 
142
155
  ## 🌐 Repo
143
156
 
144
- [https://github.com/eriksturesson/backendError](https://github.com/eriksturesson/backendError)
145
-
146
- ---
157
+ [GitHub](https://github.com/eriksturesson/backendError)
147
158
 
148
159
  Created by [@eriksturesson](https://eriksturesson.se)
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
+ "version": "1.1.1",
2
3
  "name": "backend-error",
3
4
  "license": "MIT",
5
+ "keywords": [
6
+ "error",
7
+ "error-handler",
8
+ "http-errors",
9
+ "express",
10
+ "firebase-functions",
11
+ "nodejs",
12
+ "api",
13
+ "backend",
14
+ "error-handling",
15
+ "http-status",
16
+ "custom-error",
17
+ "structured-error"
18
+ ],
4
19
  "maintainers": [
5
20
  "Erik Sturesson"
6
21
  ],
@@ -9,17 +24,7 @@
9
24
  "email": "hej@eriksturesson.se",
10
25
  "url": "https://eriksturesson.se"
11
26
  },
12
- "version": "1.1.0",
13
27
  "description": "Simple Error handling library.",
14
- "keywords": [
15
- "error",
16
- "fail",
17
- "drawing",
18
- "drawings",
19
- "summarized",
20
- "help",
21
- "fun"
22
- ],
23
28
  "repository": {
24
29
  "type": "git",
25
30
  "url": "https://github.com/eriksturesson/backendError"