error.go 1.29 KB
package handler

import (
	"errors"
	"github.com/gofiber/fiber/v3"
	"ui.ac.id/dtd/go-webserver-boilerplate/internal/domain" // Adjust import path to your project
)

func ErrorHandler(ctx fiber.Ctx, err error) error {
	if err == nil {
		return nil
	}

	code := fiber.StatusInternalServerError

	var fiberErr *fiber.Error
	if errors.As(err, &fiberErr) {
		code = fiberErr.Code
		response := NewBaseResponse(code, nil, err)
		return ctx.Status(code).JSON(response)
	}

	var customErr *domain.Error

	if errors.As(err, &customErr) {
		switch customErr.Code {
		case domain.NotFound:
			code = fiber.StatusNotFound
		case domain.Validation:
			code = fiber.StatusBadRequest
		case domain.Database:
			code = fiber.StatusInternalServerError
		case domain.InactiveUser:
			code = fiber.StatusForbidden
		case domain.Unauthorized:
			code = fiber.StatusUnauthorized
		default:
			code = fiber.StatusInternalServerError
		}
	}

	response := NewBaseResponse(code, nil, err)
	return ctx.Status(code).JSON(response)
}

func formatError(err error) ErrorResponse {
	var customErr *domain.Error
	if errors.As(err, &customErr) {
		errResp := ErrorResponse{
			Message: customErr.Message,
		}
		if customErr.Err != nil {
			errResp.Details = customErr.Err.Error()
		}
		return errResp
	}
	return ErrorResponse{
		Message: err.Error(),
	}
}