Skip to main content

Tài liệu tham khảo sentry với express

· 4 min read

Thêm @sentry/node vào package.json:

npm install --save @sentry/node

Sentry nên được khởi tạo càng sớm trong ứng dụng của bạn càng tốt:

import express from "express";
import * as Sentry from "@sentry/node";

// or using CommonJS
// const express = require('express');
// const Sentry = require('@sentry/node');

const app = express();

Sentry.init({ dsn: "https://examplePublicKey@o0.ingest.sentry.io/0" });

// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());

// All controllers should live here
app.get("/", function rootHandler(req, res) {
res.end("Hello world!");
});

// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());

// Optional fallthrough error handler
app.use(function onError(err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + "\n");
});

app.listen(3000);

Cách để kiểm thử sentry với một api và trả về lỗi :

app.get("/debug-sentry", function mainHandler(req, res) {
throw new Error("My first Sentry error!");
});

requestHandler Tùy biến một số tùy chọn cho phép bạn quyết định dữ liệu nào sẽ được đưa vào sự kiện được gửi tới Sentry.

Các tùy chọn có thể là:

// keys to be extracted from req
request?: boolean | string[]; // default: true = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']

// server name
serverName?: boolean; // default: true

// generate transaction name
// path == request.path (eg. "/foo")
// methodPath == request.method + request.path (eg. "GET|/foo")
// handler == function name (eg. "fooHandler")
transaction?: boolean | 'path' | 'methodPath' | 'handler'; // default: true = 'methodPath'

// keys to be extracted from req.user
user?: boolean | string[]; // default: true = ['id', 'username', 'email']

// client ip address
ip?: boolean; // default: false

// node version
version?: boolean; // default: true

// timeout for fatal route errors to be delivered
flushTimeout?: number; // default: undefined

Ví dụ: nếu bạn muốn bỏ qua tên máy chủ và chỉ thêm người dùng, bạn sẽ sử dụng requestHandler như sau:

app.use(
Sentry.Handlers.requestHandler({
serverName: false,
user: ["email"],
})
);

Mặc định thì errorHandler sẽ chỉ nắm bắt các lỗi với mã trạng thái là 500 hoặc cao hơn. Nếu bạn muốn thay đổi nó, hãy cung cấp cho nó shouldHandleError , chấp nhận error làm đối số của nó và quyết định xem có nên gửi lỗi hay không bằng cách trả về một giá trị boolean thích hợp.

app.use(
Sentry.Handlers.errorHandler({
shouldHandleError(error) {
// Capture all 404 and 500 errors
if (error.status === 404 || error.status === 500) {
return true;
}
return false;
},
})
);

Nếu bạn sử dụng TypeScript, bạn cần truyền trình xử lý của chúng tôi để thể hiện các loại cụ thể. Chúng hoàn toàn tương thích, vì vậy điều duy nhất bạn cần thay đổi là:

// from
const express = require('express');
// to
import * as express from 'express';


// from
app.use(Sentry.Handlers.requestHandler());
// to
app.use(Sentry.Handlers.requestHandler() as express.RequestHandler);


// from
app.use(Sentry.Handlers.errorHandler());
// to
app.use(Sentry.Handlers.errorHandler() as express.ErrorRequestHandler);

Monitor Performance

Có thể thêm theo dõi quá trình ghi nhật ký các sự kiện diễn ra trong một yêu cầu, thường là trên nhiều dịch vụ cho tất cả các khuôn khổ phổ biến. Tuy nhiên, chúng tôi chỉ cung cấp các trình xử lý mặc định cho Express.

const Sentry = require("@sentry/node");
const express = require("express");
const app = express();

Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
// enable Express.js middleware tracing
new Sentry.Integrations.Express({
// to trace all requests to the default router
app,
// alternatively, you can specify the routes you want to trace:
// router: someRouter,
}),
],

// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

// RequestHandler creates a separate execution context using domains, so that every
// transaction/span/breadcrumb is attached to its own Hub instance
app.use(Sentry.Handlers.requestHandler());
// TracingHandler creates a trace for every incoming request
app.use(Sentry.Handlers.tracingHandler());

// the rest of your app

app.use(Sentry.Handlers.errorHandler());
app.listen(3000);

Các bước được cung cấp cho các hoạt động sau trong một sentry:

  • Yêu cầu HTTP được thực hiện với request
  • get cuộc gọi sử dụng httphttps
  • Middleware (Express.js only)

Troubleshooting

Khi chụp lỗi cục bộ, hãy đảm bảo rằng bộ lọc dữ liệu của dự án để lọc các sự kiện máy chủ cục bộ đã được tắt:

express data filters

Điều này đảm bảo rằng các lỗi do trình duyệt của bạn tạo ra (chẳng hạn như lỗi do các phương thức HTTP tạo ra) được ghi lại đúng cách.