Browse the docs

Errors & Responses

Putnami provides typed HTTP exceptions and response factories for building consistent APIs with proper error handling.

HTTP exceptions

Built-in exceptions

Import and throw HTTP exceptions from @putnami/runtime:

import {
  BadRequestException,      // 400
  UnauthorizedException,    // 401
  ForbiddenException,       // 403
  NotFoundException,        // 404
  MethodNotAllowedException, // 405
  ConflictException,        // 409
  PayloadTooLargeException, // 413
  UnprocessableEntityException, // 422
  TooManyRequestsException, // 429
  InternalServerErrorException, // 500
  NotImplementedException,  // 501
  ServiceUnavailableException, // 503
} from '@putnami/runtime';

Throwing exceptions

import { endpoint, Uuid } from '@putnami/application';
import { NotFoundException, ForbiddenException } from '@putnami/runtime';

export default endpoint()
  .params({ id: Uuid })
  .handle(async (ctx) => {
    const user = await findUser(ctx.params.id);

    if (!user) {
      throw new NotFoundException(`User ${ctx.params.id} not found`);
    }

    if (!canAccess(ctx, user)) {
      throw new ForbiddenException('Access denied');
    }

    return user;
  });

Exception with details

throw new BadRequestException({
  message: 'Validation failed',
  fields: {
    email: 'Invalid email format',
    password: 'Password too short',
  },
});

Custom exceptions

Create custom exceptions by extending HttpException:

import { HttpException } from '@putnami/runtime';

export class RateLimitException extends HttpException {
  constructor(readonly retryAfter: number) {
    super(`Rate limit exceeded. Retry after ${retryAfter} seconds`, 429);
  }
}

// Usage
throw new RateLimitException(60);

Validation

The endpoint() builder validates inputs automatically. Invalid requests are rejected before your handler runs:

import { endpoint, Email, MinLength } from '@putnami/application';

export default endpoint()
  .body({ email: Email, password: MinLength(8) })
  .handle(async (ctx) => {
    const body = await ctx.body();
    // body.email and body.password are validated
  });

Context throw

Use ctx.throw() for quick error responses:

import { endpoint } from '@putnami/application';

export default endpoint((ctx) => {
  const id = ctx.queryParams()['id'];

  if (!id) {
    ctx.throw(400, 'ID is required');
  }

  return { id };
});

Typed error answers

An endpoint that declares an error status with a schema answers it with ctx.error(status, body), typed by that schema; see Typed error answers in the API guide.

Problem details (RFC 9457)

http({ problemDetails: true }) answers every error of the app as application/problem+json: exceptions, unexpected failures, unmatched routes and the framework's own refusals. One endpoint opts in alone with .problemDetails(). It is off by default.

import { endpoint, http, Int } from '@putnami/application';

// For the whole app, in its entry point:
http({ problemDetails: true });

// Or for one endpoint:
export default endpoint()
  .throws(409, 'Overdrawn', { balance: Int })
  .problemDetails()
  .handle((ctx) => ctx.error(409, { balance: -3 }));
// → 409 application/problem+json
//   { "type": "about:blank", "title": "Conflict", "balance": -3, "status": 409 }

For another exception, the status phrase is the title and the message the detail. What keeps its own format (responses the app builds, Connect, gRPC, streams, HTML error pages) is listed in the HTTP server guide.

Response factories

Creating responses

import { endpoint, HttpResponse, json } from '@putnami/application';

// JSON response
export default endpoint(() => {
  return json({ message: 'Hello' });
});

// JSON with status
export default endpoint(() => {
  return json({ created: true }, { status: 201 });
});

// Redirect
export default endpoint(() => {
  return HttpResponse.redirect('/new-location');
});

// Redirect with status
export default endpoint(() => {
  return HttpResponse.redirect('/permanent', 301);
});

Error response factories

import { badRequest, unauthorized, forbidden, notFound, internalServerError } from '@putnami/application';

// 400 Bad Request
badRequest('Invalid input');

// 401 Unauthorized
unauthorized('Authentication required');

// 403 Forbidden
forbidden('Access denied');

// 404 Not Found
notFound('Resource not found');

// 500 Internal Server Error
internalServerError('Something went wrong');

Custom headers

import { endpoint, json } from '@putnami/application';

export default endpoint(() => {
  return json({ data: 'value' })
    .setHeader('X-Request-Id', crypto.randomUUID())
    .setHeader('Cache-Control', 'max-age=3600');
});

Multiple headers with same name

import { endpoint, json } from '@putnami/application';

export default endpoint(() => {
  return json({ ok: true })
    .pushHeader('Set-Cookie', 'session=abc; HttpOnly')
    .pushHeader('Set-Cookie', 'tracking=xyz');
});

Custom response

import { endpoint, HttpResponse } from '@putnami/application';

export default endpoint(() => {
  return new HttpResponse('Plain text', {
    status: 200,
    headers: {
      'Content-Type': 'text/plain',
    },
  });
});

File download

import { endpoint, HttpResponse } from '@putnami/application';

export default endpoint(async () => {
  const file = Bun.file('report.pdf');
  const content = await file.arrayBuffer();

  return new HttpResponse(content, {
    headers: {
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename="report.pdf"',
      'Content-Length': String(content.byteLength),
    },
  });
});

Streaming response

import { endpoint, HttpResponse } from '@putnami/application';

export default endpoint(() => {
  const stream = new ReadableStream({
    async start(controller) {
      for (let i = 0; i < 10; i++) {
        controller.enqueue(`data: ${i}\n\n`);
        await new Promise(r => setTimeout(r, 1000));
      }
      controller.close();
    },
  });

  return new HttpResponse(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
    },
  });
});

Error handling patterns

Global error handler

import type { HttpMiddleware } from '@putnami/application';
import { HttpException, ValidationException } from '@putnami/runtime';
import { json, internalServerError } from '@putnami/application';

export const errorHandler: HttpMiddleware = async (ctx, next) => {
  try {
    return await next();
  } catch (error) {
    // Validation errors, checked first: ValidationException is an HttpException
    if (error instanceof ValidationException) {
      return json(
        { error: 'Validation failed', details: error.getResponse() },
        { status: 422 }
      );
    }

    // Known HTTP exceptions
    if (error instanceof HttpException) {
      return json(
        { error: error.message, code: error.getStatus() },
        { status: error.getStatus() }
      );
    }

    // Log unexpected errors
    console.error('Unexpected error:', error);

    return internalServerError('An unexpected error occurred');
  }
};

Domain-specific errors

import { endpoint, json } from '@putnami/application';

// Define domain errors
export class InsufficientFundsError extends Error {
  constructor(public available: number, public required: number) {
    super(`Insufficient funds: ${available} available, ${required} required`);
  }
}

// Handle in route
export default endpoint(async () => {
  try {
    await processPayment(amount);
    return { success: true };
  } catch (error) {
    if (error instanceof InsufficientFundsError) {
      return json(
        {
          error: 'Insufficient funds',
          available: error.available,
          required: error.required,
        },
        { status: 402 }
      );
    }
    throw error;
  }
});

Error aggregation

import { endpoint } from '@putnami/application';
import { AggregateException } from '@putnami/runtime';

export default endpoint(async (ctx) => {
  const body = await ctx.body();
  const errors: Error[] = [];

  // Collect multiple errors
  if (!isValidEmail(body.email)) {
    errors.push(new Error('Invalid email'));
  }

  if (!isValidPassword(body.password)) {
    errors.push(new Error('Invalid password'));
  }

  if (errors.length > 0) {
    throw new AggregateException(errors);
  }

  // Process valid input...
});

Response status codes

Success codes

import { endpoint, json, noContent } from '@putnami/application';

// 200 OK (default)
return { data: 'value' };

// 201 Created
return json({ id: newId }, { status: 201 });

// 204 No Content: return noContent(). Returning undefined answers 404.
export default endpoint(async () => {
  await deleteResource();
  return noContent();
});

Redirect codes

import { HttpResponse } from '@putnami/application';

// 301 Moved Permanently
HttpResponse.redirect('/new-url', 301);

// 302 Found (default)
HttpResponse.redirect('/new-url');

// 303 See Other
HttpResponse.redirect('/new-url', 303);

// 307 Temporary Redirect
HttpResponse.redirect('/new-url', 307);

Client error codes

// 400 Bad Request
throw new BadRequestException('Invalid input');

// 401 Unauthorized
throw new UnauthorizedException('Please log in');

// 403 Forbidden
throw new ForbiddenException('Not allowed');

// 404 Not Found
throw new NotFoundException('Resource not found');

// 409 Conflict
throw new ConflictException('Resource already exists');

// 422 Unprocessable Entity
throw new ValidationException(errors);

// 429 Too Many Requests
throw new TooManyRequestsException('Rate limit exceeded');

Server error codes

// 500 Internal Server Error
throw new InternalServerErrorException('Server error');

// 501 Not Implemented
throw new NotImplementedException('Feature not available');

// 503 Service Unavailable
throw new ServiceUnavailableException('Service temporarily unavailable');

Framework mistakes

A mistake in using the framework, caught at composition, build or dev time, raises an error that names the change that fixes it and the page that explains it. A schema field that is not a schema type fails when the endpoint is declared, outside production and at generation:

import { endpoint } from '@putnami/application';
export default endpoint()
  .body({ name: 'string' }) // a string, not the String constructor
  .handle(async (ctx) => ({ ok: true }));
endpoint schema field body.name is the string 'string', which is not a schema type, so it accepts any value
  File: src/api/users/post.ts:3
  Fix: write the constructor String instead of the string 'string'
  Docs: https://putnami.dev/docs/frameworks/typescript/schema#primitives

A route file whose name no route serves (src/api/items/Post.ts) is reported the same way, as a warning that keeps the build green. The error carries these facts as one structured value that mistakeOf from @putnami/runtime reads, for a terminal or another tool:

import { formatMistake, mistakeOf, type FrameworkMistake } from '@putnami/runtime';

declare const error: unknown;

const mistake: FrameworkMistake | undefined = mistakeOf(error);
// { code: 'application.invalid-schema-field', message, fix, docs, file?, line?, also? }
if (mistake) console.error(formatMistake(mistake));

A served request runs none of these checks. Every code and where it is raised are in the error handling guide; the DI errors are in Dependency Injection.