ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. error tracking
  5. Sentry Error Tracking with TypeORM in Pure JavaScript

Sentry Error Tracking with TypeORM in Pure JavaScript

In this tutorial, we’ll set up error tracking in a Node.js application using Sentry and TypeORM with MySQL. We’ll create a simple CRUD application for managing User entities and integrate Sentry for error tracking.

1. Setting Up the Project

  1. Initialize a Node.js Project
mkdir sentry-example
cd sentry-example
npm init -y

Install Dependencies

Install the necessary packages:

npm install express typeorm mysql2 @sentry/node

2. Configure Sentry

  1. Create a Sentry Account
    • Sign up at Sentry.io.
    • Create a new project (choose Node.js as your platform).
    • Get your DSN (Data Source Name) from the Sentry project settings.
  2. Configure Sentry in Your ApplicationCreate a file named sentry.js to configure Sentry:
// sentry.js
const Sentry = require('@sentry/node');

Sentry.init({
  dsn: 'YOUR_SENTRY_DSN_HERE', // Replace with your Sentry DSN
  tracesSampleRate: 1.0, // Adjust as needed
});

module.exports = Sentry;

3. Set Up TypeORM with MySQL

  1. Create a ormconfig.js FileConfigure TypeORM to connect to your MySQL database:
// ormconfig.js
module.exports = {
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root', // Replace with your MySQL username
  password: 'password', // Replace with your MySQL password
  database: 'testdb', // Replace with your database name
  entities: [__dirname + '/src/entity/*.js'],
  synchronize: true, // Set to false in production
};

Create the User Entity

Use EntitySchema for defining the User entity:

// src/entity/User.js
const { EntitySchema } = require('typeorm');

module.exports = new EntitySchema({
  name: 'User',
  tableName: 'users',
  columns: {
    id: {
      type: 'int',
      primary: true,
      generated: true,
    },
    name: {
      type: 'varchar',
      length: 255,
      nullable: false,
    },
    email: {
      type: 'varchar',
      length: 255,
      unique: true,
      nullable: false,
    },
    age: {
      type: 'int',
      nullable: false,
    },
  },
});

4. Create a Simple CRUD Application

  1. Create app.jsSet up Express, connect to the database, and create CRUD endpoints:
// app.js
const express = require('express');
const { createConnection, getRepository } = require('typeorm');
const Sentry = require('./sentry');
const User = require('./src/entity/User');

const app = express();
app.use(express.json());

// Initialize Sentry
app.use(Sentry.Handlers.requestHandler());

// Connect to the database
createConnection().then(() => {
  console.log('Connected to the database');

  // Create a new user
  app.post('/users', async (req, res) => {
    const userRepository = getRepository(User);
    try {
      const user = userRepository.create(req.body);
      await userRepository.save(user);
      res.status(201).json(user);
    } catch (error) {
      Sentry.captureException(error); // Capture and send the error to Sentry
      res.status(500).json({ message: 'Failed to create user' });
    }
  });

  // Get all users
  app.get('/users', async (req, res) => {
    const userRepository = getRepository(User);
    try {
      const users = await userRepository.find();
      res.json(users);
    } catch (error) {
      Sentry.captureException(error);
      res.status(500).json({ message: 'Failed to get users' });
    }
  });

  // Get a user by ID
  app.get('/users/:id', async (req, res) => {
    const userRepository = getRepository(User);
    try {
      const user = await userRepository.findOne(req.params.id);
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      res.json(user);
    } catch (error) {
      Sentry.captureException(error);
      res.status(500).json({ message: 'Failed to get user' });
    }
  });

  // Update a user
  app.put('/users/:id', async (req, res) => {
    const userRepository = getRepository(User);
    try {
      const user = await userRepository.findOne(req.params.id);
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      userRepository.merge(user, req.body);
      await userRepository.save(user);
      res.json(user);
    } catch (error) {
      Sentry.captureException(error);
      res.status(500).json({ message: 'Failed to update user' });
    }
  });

  // Delete a user
  app.delete('/users/:id', async (req, res) => {
    const userRepository = getRepository(User);
    try {
      const user = await userRepository.findOne(req.params.id);
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      await userRepository.remove(user);
      res.status(204).end();
    } catch (error) {
      Sentry.captureException(error);
      res.status(500).json({ message: 'Failed to delete user' });
    }
  });

  // Error handler for Sentry
  app.use(Sentry.Handlers.errorHandler());

  // Start the server
  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });
}).catch(error => {
  console.error('Database connection failed', error);
});

5. Run Your Application

  1. Start Your MySQL DatabaseMake sure your MySQL server is running and the testdb database is created.
  2. Run the Application
node app.js

Your application should now be running on http://localhost:3000, with error tracking set up using Sentry.

Brief Explanation

  • Sentry Configuration: We initialize Sentry with your DSN to track and report errors.
  • Entity Definition: EntitySchema is used to define the User entity in TypeORM.
  • Error Handling: Errors are captured and sent to Sentry using Sentry.captureException(error).

This setup allows you to handle CRUD operations with proper error tracking and reporting, making it easier to maintain and debug your application.

How can we help?