Grab response message from .NET Core API with ky

697 Views Asked by At

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: "http://localhost:62655/api",
});

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?

1

There are 1 best solutions below

0
Phil On

The ky library doesn't seem very mature but I did find this issue thread which might help ~ https://github.com/sindresorhus/ky/issues/107#issuecomment-476048453

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("http://localhost:62655/api/Order/Test", {
  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())