Sentry
เป็นตัวช่วยดักจับเหตุการณ์แบบ Real Time Software และมาในหน้าตาที่สวยงาม เพื่อให้ Developer ไม่ต้องมานั่งหาว่ามัน Error ที่ไหน
หลักการทำงานของมันคือ เมื่อ User มี Interaction ใดๆ กับ Website ของเราแล้วถ้ามันพัง Sentry จะทำการส่ง E-mail ไปบอกเราเลยว่าเห้ย! ตอนนี้ Code ของเรามันพังเพราะ Error แบบนี้อยู่นะ และเมื่อเราเข้าไปดูรายละเอียดใน Dashboard มันจะบอกว่า Error ที่เจอนี้อยู่ในไฟล์ไหน Error เพราะอะไร มี Error แบบเดียวกันกี่ครั้ง และมันจะแสดงเป็น Graph โชว์ให้เราเห็นเลย
Install
yarn add @sentry/node @sentry/tracing
Example
import express, { Application, ErrorRequestHandler, NextFunction, Request, Response } from 'express';
import * as Sentry from '@sentry/node';
import * as Tracing from '@sentry/tracing';
const port = process.env.PORT || 4000;
const app: Application = express();
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
// enable Express.js middleware tracing
new Tracing.Integrations.Express({ app }),
],
tracesSampleRate: 1.0,
debug: true,
});
// 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 error handler must be before any other error middleware and after all controllers
app.use(
Sentry.Handlers.errorHandler({
shouldHandleError(error) {
// Capture all 404 and 500 errors
if (error.status === 404 || error.status === 500) {
return true;
}
return false;
},
})
);
// Optional fallthrough error handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
res.status(500).send(err);
});
// All controllers should live here
app.get('/', (req: Request, res: Response) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Express server has started on port ${port}`);
});
app.get('/debug-sentry', (req: Request, res: Response) => {
try {
console.error('test');
throw new Error('My first Sentry error2222!');
} catch (err) {
Sentry.captureException(err);
}
});
Last updated