Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle error response codes with fetch? #1465

Closed
taha-astera opened this issue Jun 18, 2024 · 4 comments · Fixed by #1470
Closed

How to handle error response codes with fetch? #1465

taha-astera opened this issue Jun 18, 2024 · 4 comments · Fixed by #1470
Assignees
Labels
fetch Fetch client related issue

Comments

@taha-astera
Copy link

taha-astera commented Jun 18, 2024

What are the steps to reproduce this issue?

  1. I have a simple get endpoint. Orval generated this function:
export const getApiJobSearchJobs = async (params?: GetApiJobSearchJobsParams, options?: RequestInit): Promise<JobResponse[]> => {
  const res = await fetch(
    getGetApiJobSearchJobsUrl(params),
    {      
      ...options,
      method: 'GET'
      
    }
  )
  console.log(res.status);
  
  return res.json()
}
  1. If the user is not logged in my api throws a 401. And that is console logged.
  2. I tried a try catch but that doesn't get triggered. How do I handle error values?

Using with svelte 4.

This is my config:

import { defineConfig } from 'orval';
import { API_URL } from './src/lib/constants';

export default defineConfig({
	doc: {
		output: {
			baseUrl: API_URL,
			mode: 'tags-split',
			target: 'src/lib/types/server/api.ts',
			schemas: 'src/lib/types/server/models',
			client: 'fetch',
			mock: false
		},
		input: {
			target: '../swagger.json'
		}
	}
});
@melloware melloware added the fetch Fetch client related issue label Jun 18, 2024
@soartec-lab
Copy link
Member

We have no way of accepting it at the moment.
However, I'm considering expanding the response type as follows:

https://gist.github.com/anymaniax/44c1331a5643081a82da070e45f405f0#file-http-instance-ts-L68-L72

@soartec-lab
Copy link
Member

soartec-lab commented Jun 19, 2024

I would like to update the generated code as follows:

// add response type
export type listPetsResponse = {
  status: number;
  data: Pets;
};

export const listPets = async (
  params?: ListPetsParams,
  options?: RequestInit,
): Promise<listPetsResponse> => {
  const res = await fetch(getListPetsUrl(params), {
    ...options,
    method: 'GET',
  });
  const data = await res.json();

  return { status: res.status, data: data };
};

@melloware @taha-astera
What's do yo think?

@melloware
Copy link
Collaborator

sounds good to me.

@soartec-lab
Copy link
Member

related #1387

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fetch Fetch client related issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants