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,8 +166,12 @@ func (h *JobHandler) GetLog(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
count, _ := logRepo.CountByJobID(id)
|
count, _ := logRepo.CountByJobID(id)
|
||||||
w.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))
|
w.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))
|
||||||
|
if logs == nil {
|
||||||
|
writeJSON(w, []any{})
|
||||||
|
} else {
|
||||||
writeJSON(w, logs)
|
writeJSON(w, logs)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (h *JobHandler) DownloadLog(w http.ResponseWriter, r *http.Request) {
|
func (h *JobHandler) DownloadLog(w http.ResponseWriter, r *http.Request) {
|
||||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
|||||||
+22
-1
@@ -2,7 +2,9 @@ package api
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"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.RequestID)
|
||||||
r.Use(middleware.RealIP)
|
r.Use(middleware.RealIP)
|
||||||
r.Use(middleware.Logger)
|
r.Use(middleware.Logger)
|
||||||
r.Use(middleware.Recoverer)
|
r.Use(recoverer)
|
||||||
|
|
||||||
s := &Server{router: r, cfg: cfg, engine: engine}
|
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) {
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
s.router.ServeHTTP(w, r)
|
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;
|
body?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isArray(v: unknown): v is unknown[] {
|
||||||
|
return Array.isArray(v);
|
||||||
|
}
|
||||||
|
|
||||||
export async function api<T>(path: string, opts: ApiOptions = {}): Promise<T> {
|
export async function api<T>(path: string, opts: ApiOptions = {}): Promise<T> {
|
||||||
const { method = 'GET', body } = opts;
|
const { method = 'GET', body } = opts;
|
||||||
const res = await fetch(`${BASE}${path}`, {
|
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');
|
throw new Error((err as { error?: string }).error || 'Request failed');
|
||||||
}
|
}
|
||||||
if (res.status === 204) return undefined as T;
|
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> {
|
export async function apiRaw(path: string): Promise<Response> {
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export default function JobDetail() {
|
|||||||
try {
|
try {
|
||||||
const j = await api<Job>(`/api/jobs/${id}`);
|
const j = await api<Job>(`/api/jobs/${id}`);
|
||||||
setJob(j);
|
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);
|
const p = pairs.find((sp: SyncPair) => sp.id === j.sync_pair_id);
|
||||||
setPair(p || null);
|
setPair(p || null);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -91,9 +91,9 @@ export default function JobDetail() {
|
|||||||
|
|
||||||
async function loadLogs(offset: number) {
|
async function loadLogs(offset: number) {
|
||||||
try {
|
try {
|
||||||
const ls = await api<LogLine[]>(
|
const ls = (await api<LogLine[]>(
|
||||||
`/api/jobs/${id}/log?offset=${offset}&limit=1000`
|
`/api/jobs/${id}/log?offset=${offset}&limit=1000`
|
||||||
);
|
)) ?? [];
|
||||||
if (offset === 0) {
|
if (offset === 0) {
|
||||||
setLogs(ls);
|
setLogs(ls);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ export default function JobHistory() {
|
|||||||
const totalCount = res.headers.get('X-Total-Count');
|
const totalCount = res.headers.get('X-Total-Count');
|
||||||
if (totalCount) setTotal(Number(totalCount));
|
if (totalCount) setTotal(Number(totalCount));
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setJobs(data);
|
setJobs(Array.isArray(data) ? data : []);
|
||||||
} catch {
|
} catch {
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
|||||||
Reference in New Issue
Block a user