Grab Response Message From. Net Core Api with Ky

I use ky package for sending HTTP requests to web api. Everything works except handling error messages.

Let me show you my source code:

// api method
[HttpPost("Test")]
public async Task<IActionResult> Test([FromBody] TestViewModel model)
{
    if(model.Test)
    {
        return StatusCode(StatusCode.Status200OK, "Success message");
    }
    else
    {
        return StatusCode(StatusCodes.Status500InternalServerError, "Error message");
    }
}

My aim is get and display Success message or Error message text on the frontend.

Client side:

//webclient.js
import ky from "ky";

export const webclient = ky.create({
  prefixUrl: "",
});

Firing API call:

//testAPI.js
import { webclient } from '../../common/webclient';

const result = await webclient.post('Order/Test', { json: { ...model } }).json();
console.log(result);

If the status code is equal to 200 the message (Success message) show in console properly, but for 500 (or 400, or any else) console remains empty.

DevTools confirm that API returns 500 status code with message Error message so it's not an API problem.

The question is: how can I obtain an error message with ky?

7

1 Answer

The ky library doesn't seem very mature but I did find this issue thread which might help ~

I would strongly suggest you just stick to vanilla fetch where you're in full control of handling the response text if required

const response = await fetch("", {
  method: "POST",
  headers: { "Content-type": "application/json" },
  body: JSON.stringify({ ...model })
})

if (!response.ok) {
  throw new Error(`${response.status}: ${await response.text()}`)
} 
console.log(await response.json())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest