Fix: defensive frontend + panic recovery logging middleware
Frontend: - JobDetail loadLogs: fallback to [] when API returns null - JobDetail loadJob: pairs ?? [] guard on /api/sync-pairs 500 - JobHistory: Array.isArray guard on job list response - api client: return undefined for null body instead of throwing Backend: - handlers_jobs GetLog: return [] instead of null when no log rows - router: custom recoverer middleware that logs panics to slog with full stack trace, method, and path
This commit is contained in:
@@ -166,7 +166,11 @@ func (h *JobHandler) GetLog(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
count, _ := logRepo.CountByJobID(id)
|
||||
w.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))
|
||||
writeJSON(w, logs)
|
||||
if logs == nil {
|
||||
writeJSON(w, []any{})
|
||||
} else {
|
||||
writeJSON(w, logs)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *JobHandler) DownloadLog(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+22
-1
@@ -2,7 +2,9 @@ package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
@@ -26,7 +28,7 @@ func NewServer(cfg *config.Config, db *sql.DB, engine *syncengine.Engine) *Serve
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(recoverer)
|
||||
|
||||
s := &Server{router: r, cfg: cfg, engine: engine}
|
||||
|
||||
@@ -101,3 +103,22 @@ func NewServer(cfg *config.Config, db *sql.DB, engine *syncengine.Engine) *Serve
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.router.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func recoverer(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
slog.Error("panic recovered",
|
||||
"error", err,
|
||||
"stack", string(debug.Stack()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ interface ApiOptions {
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
function isArray(v: unknown): v is unknown[] {
|
||||
return Array.isArray(v);
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, opts: ApiOptions = {}): Promise<T> {
|
||||
const { method = 'GET', body } = opts;
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
@@ -18,7 +22,10 @@ export async function api<T>(path: string, opts: ApiOptions = {}): Promise<T> {
|
||||
throw new Error((err as { error?: string }).error || 'Request failed');
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
const data = await res.json().catch(() => null);
|
||||
if (data === null) return undefined as T;
|
||||
if (isArray(data) && !data.length && data[0] === undefined) return [] as unknown as T;
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export async function apiRaw(path: string): Promise<Response> {
|
||||
|
||||
@@ -80,7 +80,7 @@ export default function JobDetail() {
|
||||
try {
|
||||
const j = await api<Job>(`/api/jobs/${id}`);
|
||||
setJob(j);
|
||||
const pairs = await api<SyncPair[]>('/api/sync-pairs');
|
||||
const pairs = (await api<SyncPair[]>('/api/sync-pairs')) ?? [];
|
||||
const p = pairs.find((sp: SyncPair) => sp.id === j.sync_pair_id);
|
||||
setPair(p || null);
|
||||
} catch {
|
||||
@@ -91,9 +91,9 @@ export default function JobDetail() {
|
||||
|
||||
async function loadLogs(offset: number) {
|
||||
try {
|
||||
const ls = await api<LogLine[]>(
|
||||
const ls = (await api<LogLine[]>(
|
||||
`/api/jobs/${id}/log?offset=${offset}&limit=1000`
|
||||
);
|
||||
)) ?? [];
|
||||
if (offset === 0) {
|
||||
setLogs(ls);
|
||||
} else {
|
||||
|
||||
@@ -60,7 +60,7 @@ export default function JobHistory() {
|
||||
const totalCount = res.headers.get('X-Total-Count');
|
||||
if (totalCount) setTotal(Number(totalCount));
|
||||
const data = await res.json();
|
||||
setJobs(data);
|
||||
setJobs(Array.isArray(data) ? data : []);
|
||||
} catch {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
Reference in New Issue
Block a user