0Pricing
Node.js Backend Development Bootcamp · 강의

전역 오류 처리 전략

중앙 집중식 오류 처리 메커니즘을 구현하여 예외를 우아하게 관리하고 일관된 오류 응답을 제공합니다.

전역 오류 처리 전략은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Centralized Errors in Express

When building an API, errors are inevitable. How you handle them can drastically affect user experience and application stability.

Scattered try...catch blocks in every route can become messy and inconsistent. This lesson introduces global error handling in Express.js.

Express's Default Error Response

By default, if an error occurs in an Express route or middleware and isn't caught, Express will:

  • Send a response with a 500 Internal Server Error status code.
  • Include the error's stack trace in the response.

This default behavior is not ideal for production, as it exposes sensitive server details to clients.

The Special Error Middleware

Express recognizes a special type of middleware for error handling. Unlike regular middleware which takes (req, res, next), error-handling middleware takes four arguments:

  • err: The error object passed by Express.
  • req: The request object.
  • res: The response object.
  • next: The next middleware function.

Express knows to skip all other middleware and send the error directly to this special handler.

Your First Error Middleware

Let's create a basic error handling middleware. This middleware should be placed after all other routes and middleware in your app.js file.

Try running this simple Express app:

const express = require('express');
const app = express();

// A route that intentionally throws an error
app.get('/error', (req, res, next) => {
  const err = new Error('Something went wrong!');
  err.statusCode = 400;
  next(err); // Pass the error to the error middleware
});

// Global Error Handling Middleware (must be last)
app.use((err, req, res, next) => {
  console.error(err.stack); // Log the error for debugging
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    status: 'error',
    message: err.message || 'An unexpected error occurred!'
  });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Visit http://localhost:3000/error to see error handling');
});

Operational vs. Programmatic Errors

It's crucial to distinguish between error types:

  • Operational Errors: Predictable errors from system operations (e.g., invalid user input, network issues, resource not found). These are 'soft' errors we can handle gracefully and send specific messages to the client.
  • Programmatic Errors: Bugs in your code (e.g., trying to read property of undefined, database connection failures). These are 'hard' errors that indicate a problem with your application logic and might require restarting the process.

Our global handler should treat these differently.

Crafting Custom Errors

To better categorize and handle errors, we can create custom error classes. This allows us to attach specific properties like statusCode and isOperational to our errors.

Here's a simple AppError class:

// utils/appError.js
class AppError extends Error {
  constructor(message, statusCode) {
    super(message);

    this.statusCode = statusCode;
    this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
    this.isOperational = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

module.exports = AppError;

Using Custom Errors in Routes

Now that we have our AppError class, we can use it in our routes to throw specific, operational errors. When an AppError is thrown and caught by next(err), our global handler can provide a tailored response.

Run this example and try visiting /user/123 (valid) and /user/abc (invalid ID):

const express = require('express');
const AppError = require('./utils/appError'); // Assuming appError.js is in a 'utils' folder
const app = express();

// Example route using custom error
app.get('/user/:id', (req, res, next) => {
  const userId = parseInt(req.params.id);

  if (isNaN(userId)) {
    return next(new AppError('Invalid user ID provided!', 400));
  }

  res.status(200).json({
    status: 'success',
    data: { id: userId, name: `User ${userId}` }
  });
});

// Global Error Handling Middleware (must be last)
app.use((err, req, res, next) => {
  console.error(err.stack);

  const statusCode = err.statusCode || 500;
  const status = err.status || 'error';

  if (err.isOperational) {
    res.status(statusCode).json({
      status: status,
      message: err.message
    });
  } else {
    // For programmatic errors, send a generic message in production
    res.status(500).json({
      status: 'error',
      message: 'Something went very wrong!'
    });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Visit http://localhost:3000/user/1 to see success');
  console.log('Visit http://localhost:3000/user/abc to see custom error');
});

// --- Create utils/appError.js with the content from the previous scene for this to run ---

Intelligent Error Responses

Our error handler can be further refined to provide different responses based on the environment (development vs. production).

  • Development: Send full error details (stack trace) for debugging.
  • Production: Send minimal, user-friendly messages for operational errors and generic messages for programmatic errors (to hide internal details).

This approach keeps your API secure and informative.

Catching the Unforeseen

Express middleware only catches errors that occur within the request-response cycle and are passed with next(err). What about errors outside of this?

  • Uncaught Exceptions: Synchronous errors that are not handled by any try...catch block.
  • Unhandled Rejections: Promise rejections that don't have a .catch() handler.

Node.js provides global process event listeners for these critical errors, which should ideally shut down the application after logging the error.

// In your server.js or app.js, before app.listen
process.on('uncaughtException', err => {
  console.error('UNCAUGHT EXCEPTION! Shutting down...');
  console.error(err.name, err.message, err.stack);
  process.exit(1); // Exit with failure code
});

// After app.listen, for unhandled promise rejections
process.on('unhandledRejection', err => {
  console.error('UNHANDLED REJECTION! Shutting down...');
  console.error(err.name, err.message);
  // Optionally close server first, then exit
  server.close(() => {
    process.exit(1);
  });
});

Error Handling Challenge

You've learned about Express error handling. Which of the following is the correct signature for an Express error handling middleware?

Global Error Handling Summary

Great job! You've learned how to implement robust error handling in your Express applications.

  • Express uses a special 4-argument middleware for error handling.
  • Distinguish between operational and programmatic errors.
  • Create custom error classes to add context to your errors.
  • Implement global listeners for uncaught exceptions and unhandled rejections.

Centralized error handling makes your API more reliable, secure, and easier to debug!

자주 묻는 질문

“전역 오류 처리 전략” 강의는 무료인가요?

네 — “전역 오류 처리 전략” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“전역 오류 처리 전략”에서 뭘 배우나요?

중앙 집중식 오류 처리 메커니즘을 구현하여 예외를 우아하게 관리하고 일관된 오류 응답을 제공합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“전역 오류 처리 전략” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 정의 Express 미들웨어 개발
  2. 전역 오류 처리 전략
  3. Joi/Express-Validator로 입력값 검증
  4. JWT를 사용한 인증 미들웨어
← Node.js Backend Development Bootcamp(으)로 돌아가기