Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(web): show readable request validation errors (#6902)

LearningCircuit015e93086b47
diff --git a/changelog.d/+readable-validation-errors.bugfix.md b/changelog.d/+readable-validation-errors.bugfix.md
new file mode 100644
index 0000000000..9b619c3af2
--- /dev/null
+++ b/changelog.d/+readable-validation-errors.bugfix.md
@@ -0,0 +1 @@
+Show readable field errors for FastAPI validation failures instead of `[object Object]`. This changes the 422 contract for `/api/v1` clients: the response gains an `error` string, each `detail` entry keeps `loc` and `type` but its `msg` is now fixed text per error type, and the `input`, `ctx` and `url` keys are no longer returned.
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index 6c0e8aa33f..7748aba137 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -1264,10 +1264,82 @@ def _is_api_request(request: Request) -> bool:
def _register_exception_handlers(app: FastAPI) -> None:
"""Register custom exception handlers (ports Flask's error handlers)."""
- from fastapi.exceptions import HTTPException
+ from fastapi.exceptions import HTTPException, RequestValidationError
from .exceptions import WebAPIException
+ # Pydantic's ``msg`` can contain submitted values when a validator raises
+ # ValueError or PydanticCustomError. Build the browser summary and the
+ # structured detail from fixed messages keyed by error type instead.
+ safe_validation_messages = {
+ "missing": "Field required",
+ "extra_forbidden": "Unexpected field",
+ "json_invalid": "Invalid JSON",
+ "int_parsing": "Enter a valid integer",
+ "int_type": "Enter a valid integer",
+ "float_parsing": "Enter a valid number",
+ "float_type": "Enter a valid number",
+ "bool_parsing": "Enter true or false",
+ "bool_type": "Enter true or false",
+ "string_type": "Enter text",
+ "string_too_short": "Text is too short",
+ "string_too_long": "Text is too long",
+ "greater_than": "Value is too small",
+ "greater_than_equal": "Value is too small",
+ "less_than": "Value is too large",
+ "less_than_equal": "Value is too large",
+ "literal_error": "Choose an allowed value",
+ "list_type": "Enter a list",
+ "dict_type": "Enter an object",
+ }
+
+ @app.exception_handler(RequestValidationError)
+ async def handle_request_validation_error(
+ request: Request, exc: RequestValidationError
+ ):
+ # Keep ``loc``/``type`` for API clients, replace every ``msg`` with
+ # fixed text, drop ``input``/``ctx``/``url``, and add the ``error``
+ # string consumed by the browser. Validator messages and submitted
+ # values are never forwarded. ``loc`` is copied as-is, so it can still
+ # echo submitted dict keys (no current route has a dict-typed or
+ # extra=forbid body); for json_invalid it ends in a parser offset.
+ errors = [
+ {
+ "loc": error["loc"],
+ "msg": safe_validation_messages.get(
+ error["type"], "Invalid value"
+ ),
+ "type": error["type"],
+ }
+ for error in exc.errors()
+ ]
+ messages = []
+ for error in errors[:3]:
+ location = error["loc"]
+ if location and location[0] in (
+ "body",
+ "query",
+ "path",
+ "header",
+ "cookie",
+ ):
+ location = location[1:]
+ field = ".".join(str(part) for part in location)
+ if error["type"] == "json_invalid" and location:
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: JSON error position is a response label and never reaches SQL
+ field = f"position {location[-1]}"
+ messages.append(
+ f"{field}: {error['msg']}" if field else error["msg"]
+ )
+ message = "Invalid request"
+ if messages:
+ message += ": " + "; ".join(messages)
+ if len(errors) > 3:
+ message += f"; and {len(errors) - 3} more validation errors"
+ return JSONResponse(
+ {"error": message, "detail": errors}, status_code=422
+ )
+
@app.exception_handler(HTTPException)
async def handle_http_exception(request: Request, exc: HTTPException):
"""Redirect 401s for browser requests to login page (Flask parity)."""
diff --git a/src/local_deep_research/web/static/js/components/save_to_collection.js b/src/local_deep_research/web/static/js/components/save_to_collection.js
index a4986cbb80..41d902c132 100644
--- a/src/local_deep_research/web/static/js/components/save_to_collection.js
+++ b/src/local_deep_research/web/static/js/components/save_to_collection.js
@@ -74,7 +74,7 @@
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(
- data.detail || data.error || `Server returned ${response.status}`
+ data.error || data.detail || `Server returned ${response.status}`
);
}
@@ -206,7 +206,7 @@
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(
- data.detail || data.error || `Server returned ${response.status}`
+ data.error || data.detail || `Server returned ${response.status}`
);
}
diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.js
index 83dd8be78c..b6750768b2 100644
--- a/src/local_deep_research/web/static/js/components/settings_sync.js
+++ b/src/local_deep_research/web/static/js/components/settings_sync.js
@@ -30,7 +30,7 @@ function performMenuSettingSave(settingKey, settingValue) {
data = {};
}
if (!response.ok) {
- const message = data.detail || data.error || data.message
+ const message = data.error || data.detail || data.message
|| `HTTP ${response.status}`;
SafeLogger.error('Error response body:', message);
throw new Error(message);
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 2bbf9eec18..f7a95fa113 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -382,7 +382,7 @@ async function dismissWarning(dismissKey) {
const data = await response.json();
if (!response.ok || data.status !== 'success') {
throw new Error(
- data.detail || data.message || data.error || 'Failed to dismiss warning'
+ data.error || data.message || data.detail || 'Failed to dismiss warning'
);
}
// Update global settings cache
diff --git a/tests/js/components/save-to-collection-runtime.test.js b/tests/js/components/save-to-collection-runtime.test.js
index 4c3cbbb38c..8df743438f 100644
--- a/tests/js/components/save-to-collection-runtime.test.js
+++ b/tests/js/components/save-to-collection-runtime.test.js
@@ -115,9 +115,15 @@ it('loads collections, safely renders them, and POSTs the selected collection',
expect(success.querySelector('img')).toBeNull();
});
-it('renders a FastAPI detail when loading collections is rejected', async () => {
+it.each([
+ { detail: 'Collection service is unavailable' },
+ {
+ error: 'Collection service is unavailable',
+ detail: [{ loc: ['query', 'limit'], msg: 'Invalid limit', type: 'int_parsing' }],
+ },
+])('renders a readable error when loading collections is rejected: %j', async body => {
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response(
- JSON.stringify({ detail: 'Collection service is unavailable' }),
+ JSON.stringify(body),
{ status: 503 },
))));
await import('@js/components/save_to_collection.js');
@@ -135,7 +141,13 @@ it('renders a FastAPI detail when loading collections is rejected', async () =>
.toBe('none');
});
-it('restores collection choices after a rejected save with FastAPI detail', async () => {
+it.each([
+ { detail: 'Research is already saved to this collection' },
+ {
+ error: 'Research is already saved to this collection',
+ detail: [{ loc: ['body', 'collection_id'], msg: 'Invalid collection', type: 'value_error' }],
+ },
+])('restores collection choices after a rejected save: %j', async body => {
const fetchMock = vi.fn((url, options = {}) => {
if (url === '/library/api/collections' && !options.method) {
return Promise.resolve(new Response(JSON.stringify({
@@ -147,9 +159,7 @@ it('restores collection choices after a rejected save with FastAPI detail', asyn
}), { status: 200 }));
}
if (options.method === 'POST') {
- return Promise.resolve(new Response(JSON.stringify({
- detail: 'Research is already saved to this collection',
- }), { status: 409 }));
+ return Promise.resolve(new Response(JSON.stringify(body), { status: 409 }));
}
throw new Error(`Unexpected request: ${url}`);
});
diff --git a/tests/js/components/settings-sync-runtime.test.js b/tests/js/components/settings-sync-runtime.test.js
index 691ffd5881..f7f6ffdb5a 100644
--- a/tests/js/components/settings-sync-runtime.test.js
+++ b/tests/js/components/settings-sync-runtime.test.js
@@ -95,9 +95,15 @@ it('persists a provider change through the FastAPI setting route and refreshes w
);
});
-it('surfaces a rejected FastAPI setting write without reporting success', async () => {
+it.each([
+ { detail: 'unsupported search engine' },
+ {
+ error: 'unsupported search engine',
+ detail: [{ loc: ['body', 'value'], msg: 'unsupported search engine', type: 'value_error' }],
+ },
+])('surfaces a rejected FastAPI setting write without reporting success: %j', async body => {
const fetchMock = vi.fn().mockResolvedValue(new Response(
- '{"detail":"unsupported search engine"}',
+ JSON.stringify(body),
{ status: 422, statusText: 'Unprocessable Entity' },
));
vi.stubGlobal('fetch', fetchMock);
diff --git a/tests/js/services/api.test.js b/tests/js/services/api.test.js
index 36f794e6bb..7ce5226daa 100644
--- a/tests/js/services/api.test.js
+++ b/tests/js/services/api.test.js
@@ -230,6 +230,20 @@ describe('fetchWithErrorHandling — 401 handling', () => {
.toBe(true);
});
+ it('shows a validation summary while retaining the structured detail array', async () => {
+ const body = {
+ error: 'Invalid request: limit: Input should be a valid integer',
+ detail: [{ loc: ['query', 'limit'], msg: 'Input should be a valid integer', type: 'int_parsing' }],
+ };
+ globalThis.fetch = vi.fn(() => Promise.resolve(new Response(
+ JSON.stringify(body), { status: 422 },
+ )));
+ const error = await fetchWithErrorHandling('/api/history').catch(value => value);
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toBe(body.error);
+ expect(error.details.detail).toEqual(body.detail);
+ });
+
it('does not attach details when the error body is JSON null', async () => {
globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(
diff --git a/tests/web/test_request_validation_messages.py b/tests/web/test_request_validation_messages.py
new file mode 100644
index 0000000000..da714e9024
--- /dev/null
+++ b/tests/web/test_request_validation_messages.py
@@ -0,0 +1,132 @@
+"""Readable 422 responses through the application's real exception handlers."""
+
+import pytest
+from fastapi import FastAPI, HTTPException, Query
+from fastapi.testclient import TestClient
+from pydantic import BaseModel, Field, field_validator
+
+from local_deep_research.web.fastapi_app import _register_exception_handlers
+
+
+class _Payload(BaseModel):
+ title: str
+ count: int = Field(gt=0)
+
+
+class _SensitivePayload(BaseModel):
+ password: str
+
+ @field_validator("password")
+ @classmethod
+ def reject_password(cls, value: str) -> str:
+ raise ValueError(f"rejected {value}")
+
+
+def client():
+ app = FastAPI()
+ _register_exception_handlers(app)
+
+ @app.post("/api/example")
+ @app.post("/api/v1/example")
+ def example(payload: _Payload):
+ return payload.model_dump()
+
+ @app.get("/api/example")
+ def query_example(limit: int = Query(gt=0)):
+ return {"limit": limit}
+
+ @app.get("/api/denied")
+ def denied():
+ raise HTTPException(status_code=403, detail="Action unavailable")
+
+ @app.post("/api/sensitive")
+ def sensitive(payload: _SensitivePayload):
+ return payload.model_dump()
+
+ with TestClient(app) as test_client:
+ yield test_client
+
+
+def test_body_errors_have_a_readable_summary_and_structured_fields(client):
+ response = client.post("/api/example", json={"count": 0})
+ assert response.status_code == 422
+ body = response.json()
+ assert isinstance(body["error"], str)
+ assert "title: Field required" in body["error"]
+ assert "count: Value is too small" in body["error"]
+ assert {tuple(error["loc"]) for error in body["detail"]} == {
+ ("body", "title"),
+ ("body", "count"),
+ }
+ assert {error["type"] for error in body["detail"]} == {
+ "missing",
+ "greater_than",
+ }
+
+
+def test_query_error_names_the_field(client):
+ response = client.get("/api/example", params={"limit": "many"})
+ assert response.status_code == 422
+ assert response.json()["error"].startswith("Invalid request: limit:")
+ assert response.json()["detail"][0]["type"] == "int_parsing"
+
+
+def test_validation_response_does_not_echo_submitted_values(client):
+ secret = "private-value-for-validation-test"
+ response = client.post(
+ "/api/example", json={"title": {"credential": secret}, "count": 0}
+ )
+ assert response.status_code == 422
+ assert secret not in response.text
+ for error in response.json()["detail"]:
+ assert set(error) == {"loc", "msg", "type"}
+
+
+def test_custom_validator_message_cannot_echo_submitted_secret(client):
+ secret = "synthetic-secret-for-validator-test"
+ response = client.post("/api/sensitive", json={"password": secret})
+
+ assert response.status_code == 422
+ assert secret not in response.text
+ assert (
+ response.json()["error"] == "Invalid request: password: Invalid value"
+ )
+ assert response.json()["detail"] == [
+ {
+ "loc": ["body", "password"],
+ "msg": "Invalid value",
+ "type": "value_error",
+ }
+ ]
+
+
+def test_invalid_json_has_a_readable_error(client):
+ response = client.post(
+ "/api/example",
+ content="{",
+ headers={"Content-Type": "application/json"},
+ )
+ assert response.status_code == 422
+ assert isinstance(response.json()["error"], str)
+ assert response.json()["detail"][0]["type"] == "json_invalid"
+ assert response.json()["error"] == (
+ "Invalid request: position 1: Invalid JSON"
+ )
+
+
+def test_programmatic_api_keeps_its_error_key(client):
+ response = client.post("/api/v1/example", json={})
+ assert response.status_code == 422
+ assert response.json()["error"].startswith("Invalid request:")
+ assert isinstance(response.json()["detail"], list)
+
+
+def test_valid_payload_and_http_exception_keep_their_contracts(client):
+ payload = {"title": "A valid title", "count": 2}
+ response = client.post("/api/example", json=payload)
+ assert response.status_code == 200
+ assert response.json() == payload
+ denied = client.get("/api/denied")
+ assert denied.status_code == 403
+ assert denied.json() == {"detail": "Action unavailable"}