teleren/devto huggingface dataset:
Nuxt3 : API error handling
Tags: nuxt, errors, api, nuxt3
Published: 2024-03-13 20:38:07

## Hello World

First post here, hello world!

## Context

- Nuxt 3.10.3
- Vue 3.4.15

In **Nuxt 3.10.3** you can't retrieve custom error message properly.

If you write a custom error message you cannot be able to retrieve it without a little but dirty workaround.

## Example

Here is a short example : 

1. A simple API event handler throwing a basic error
2. A simple page with 2 actions:
  - getting an error with `$fetch()`
  - getting an error with `useFetch()`
  - and displaying the result

```html
# /pages/error.vue

<template>
	<p><button @click="onClickFetch">GetError with $fetch()</button></p>
	<p><button @click="onClickUseFetch">GetError with useFetch()</button></p>
	<pre v-if="myError">
- statusCode: {{ myError.statusCode }}
- statusMessage: {{ myError.statusMessage }}
- message: {{ myError.message }}
- data: {{ myError.data }}
	</pre>
</template>

<script setup lang="ts">
const myError = useState('myError')

const onClickFetch = async e => {
	myError.value = null;
	try {
		const data = await $fetch('/api/error')
	} catch (error) {
		myError.value = error
	}
}

const onClickUseFetch = async e => {
	myError.value = null;
	const { data, error, execute, pending, refresh, status } = await useFetch('/api/error')
	myError.value = error
}
</script>
```

```ts
# /server/api/error.ts

export default defineEventHandler(async event => {
    throw createError({
        statusCode: 500,
        statusMessage: 'MyError statusMessage (éàè)',
        message: 'MyError message (éàè)'
        data: {
            data: {
                message: `MyError data message (éàè)`,
            },
        },
    })
})
```

Result
```
- statusCode: 500
- statusMessage: Internal Server Error
- message: [GET] "/api/error": 500 Internal Server Error
- data:
{
    data: {
        message: `MyError data message (éàè)`,
    },
}
```

As you can see, `.statusMessage` and `.message` are not returning your custom message.

## Workaround

Dirty workaround : use `.data` to pass your custom error message.

```ts
# /server/api/error.ts

export default defineEventHandler(async event => {
    throw createError({
        statusCode: 500,
        statusMessage: 'Internal Server Error',
        // Here we have to define the `data` property
        data: {
            message: `My custom error message`,
        },
    })
})
```

```html
<template>
	<div v-if="myError">
		<!-- Here we have to use .data.data.message -->
		<p>{{ myError.data.data.message }}</p>
	</div>
</template>

<script setup lang="ts">
const myError = useState('myError')

try {
	const data = await $fetch('/api/error')
} catch (error) {
	myError.value = error
}
</script>
```

It's dirty because your have to do 2 things :
1. writing the `data` block on every error you want to throw
2. using `.data.data.message` every time you want to display your message

Not found a better solution from now.


If you know a better solution, please, let us know in comment.
Scale font size the right way.
Tags: webdev, css, beginners, responsive
Published: 2024-03-13 21:05:51

Hey there, I recently found this simple way of organising font sizes for different html semantics like h1, h2, p etc and also maintain the visual hierarchy among them. 

Here is the snippet of it.

```css
root: {
    --p: 1rem;
    --font-scale: 1.2;
    --h5: calc(var(--p) * var(--font-scale));
    --h4: calc(var(--h5) * var(--font-scale));
    --h3: calc(var(--h4) * var(--font-scale));
    --h2: calc(var(--h3) * var(--font-scale));
    --h1: calc(var(--h2) * var(--font-scale));
}
```

This has mainly two benefits: 
**first:** you always maintain the hierarchy, the magnitude depends on what you set for `--font-scale` variable so tinker with it to get your perfect size.
**second:** when building responsive web apps with media queries, you only have to apply media query for `--p`, the rest will scale w.r.t to that value.

Configure this in your Tailwind config to use these variables.

```js
const config = {
 theme: {
  extend: {
   fontSize: {
     p: "var(--p)",
     h5: "var(--h5)",
     h4: "var(--h4)",
     h3: "var(--h3)",
     h2: "var(--h2)",
     h1: "var(--h1)",
    },
  }
 }
}

```
I hope this helps bring font size consistency in your next project. 


Follow me [twitter].(https://twitter.com/kuntashTweets/)
I also run a small web agency [actualizeui](https://www.actualizeui.com/).
Remote Image Provider for ImageSharp
Tags: umbraco, dotnet, imagesharp
Published: 2024-03-13 20:39:28

---
title: Remote Image Provider for ImageSharp
published: true
description: Want to process remote images using ImageSharp? I've got you!
tags: umbraco,dotnet,imagesharp
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozzethock3836x2mmf5p.jpg
---

When integrating websites with third parties, you are often required to show images from third parties too.

I don't like not having control over these images, this being either their dimensions, their formats or simply just the availability.

Using Umbraco, I've become addicted to having the control I need over images. Being able to define crops, resize them, and deliver optimal imageformats (eg. WebP) to the end user.

This is easy with my own images. Umbraco comes with ImageSharp, a fantastic product that does all kinds of image magic, to help me with delivering just the right amount of image I need.

But getting images from third parties, I am left to use only what the third party provides. Not optimal.

So I've made a provider for ImageSharp, that can download images from certain URLs, and run them through the machinery to get me the control I need.

You can too - it's on NuGet as [ImageSharpCommunity.Providers.Remote](https://www.nuget.org/packages/ImageSharpCommunity.Providers.Remote/#readme-body-tab). It's simple to [setup](https://github.com/skttl/ImageSharpCommunity.Providers.Remote/blob/main/docs/setup.md), [configure](https://github.com/skttl/ImageSharpCommunity.Providers.Remote/blob/main/docs/configure.md) and [use](https://github.com/skttl/ImageSharpCommunity.Providers.Remote/blob/main/docs/setup.md), and lets you load external images like they are your own.

If you are using Umbraco, I've made it even easier to [setup](https://github.com/skttl/ImageSharpCommunity.Providers.Remote/blob/main/docs/setup-umbraco.md), by registering everything for you - you just need to configure it.

Get the Umbraco package from the [Umbraco Marketplace](https://marketplace.umbraco.com/package/umbraco.community.imagesharpremoteimages).

Photo by <a href="https://unsplash.com/@sigmund?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Sigmund</a> on <a href="https://unsplash.com/photos/black-flat-screen-tv-turned-on-near-green-plant-eTgMFFzroGc?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
Creating an easy algorithm in F#🦊
Tags: programming, beginners, tutorial, fsharp
Published: 2024-03-13 20:31:43

I've been programming in C# for the last 8 years, but now I decided to learn a new functional programming language and my choice was F#.

One of the best ways to learn a new programming language is to practice algorithms in the new language.

So today let's create an easy algorithm in F#. This algorithm is very common in programming challenges websites like Hackerrank, Leetcode, and others...

The algorithm consists of the sum of all elements in an array and then prints the result. As I said, this is very easy.

So, to create the sample application in F# you must install the last [.NET SDK](https://dotnet.microsoft.com/en-us/download).

This tutorial will use the Visual Studio Code and the extension [Ionide for F#](https://ionide.io).

Then, write the following code in the terminal:

```bash
dotnet new console -lang "F#" -o ArraySumPractice
```
So, open the folder with your favorite IDE, I recommend the Visual Studio Code.

In the Program.fs file add the code below:

```fsharp
let arr = [|1; 2; 3; 4; 10; 11|]
let totalsum = Array.sum arr

printf "The total sum is %d\n" totalsum
```
Here we declared a variable called `arr` that receives an array with some integer values, and then we declared another variable called `totalsum` that receives the sum of all the values in the array. Finally, the total value is printed in the console.

To execute this code, select all code, and then in Windows hold the `Alt` key and hit `Enter` and in macOS hold the `Option` key and hit `Enter` this command will open a terminal window pop up on the bottom of the screen, and it should look similar to this:

![Running the code in VS Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0o22t5azx0sj46t9u3kt.png)

Note that the phrase `The total sum is 31` is displayed on the window, and now our algorithm is finished.

The same code in C# can be written as follows:

```csharp
int[] arr = [1, 2, 3, 4, 10, 11];
int totalSum = arr.Sum();

Console.WriteLine($"The total sum is {totalSum}");
```
Navigating challenges of women with color in leadership role
Published: 2024-03-13 20:25:26

In today's corporate landscape, being a woman of color in a leadership role comes with its own set of challenges and opportunities. As a brown woman navigating the realms of leadership, it's essential to recognize the unique perspective and value you bring to the table. Effectively making your voice heard requires a blend of confidence, assertiveness, and strategic communication.

First and foremost, owning your identity and embracing your unique perspective is paramount. As a brown woman, your experiences, insights, and cultural background offer a distinct lens through which to approach leadership challenges. Embrace your heritage and leverage it as a strength rather than viewing it as a barrier. By staying true to your authentic self, you not only enrich discussions with diverse viewpoints but also inspire others to appreciate the richness of cultural diversity within leadership.

Secondly, cultivating effective communication skills is essential for amplifying your voice in leadership settings. Speak with clarity, conviction, and purpose, ensuring that your message resonates with your audience. Don't shy away from advocating for yourself and articulating your ideas confidently. Additionally, actively seek opportunities to engage in meaningful dialogue, whether it's through team meetings, presentations, or networking events. By consistently voicing your perspectives and contributions, you assert your presence and establish yourself as a valuable leader within your organization.

Lastly, build alliances and allies who champion diversity and inclusivity within the workplace. Surround yourself with individuals who amplify your voice and support your professional growth. Forming strategic partnerships with like-minded colleagues and mentors can provide invaluable guidance, advocacy, and opportunities for advancement. Additionally, advocate for inclusive practices and policies that promote diversity at all levels of the organization. By fostering an inclusive environment where diverse voices are valued and heard, you pave the way for greater representation and empowerment of brown women in leadership roles.
Elevating Project Success through Proactive Risk Management: The Imperative for Technical Program Manager
Published: 2024-03-13 20:20:08



In the landscape of project management, the significance of robust risk management cannot be overstated. As custodians of project success, Technical Program Managers (TPMs) bear the responsibility of not only identifying potential risks but also proactively mitigating them to ensure smooth project execution and delivery. Herein lies the essence of effective risk management – a practice that demands vigilance, foresight, and strategic planning.

The first step in this endeavor is for TPMs to actively seek out risks that may impede project progress or jeopardize its objectives. This involves conducting thorough risk assessments, scrutinizing project components, and engaging stakeholders to identify potential vulnerabilities. By adopting a proactive stance towards risk identification, TPMs can preemptively address issues before they escalate into significant impediments.

Subsequently, TPMs must establish a comprehensive risk log that serves as a centralized repository for cataloging identified risks. This log should capture pertinent details such as the nature of the risk, its potential impact, probability of occurrence, and proposed mitigation strategies. By maintaining a structured risk log, TPMs not only gain visibility into potential threats but also facilitate informed decision-making and prioritization.

Equally crucial is the diligent tracking of risk status throughout the project lifecycle. TPMs must regularly update the risk log, monitor the progression of identified risks, and assess their evolving impact on project milestones. Additionally, they should flag critical risks and bottlenecks to ensure timely intervention and resolution.

Moreover, TPMs must take proactive measures to develop robust mitigation plans aimed at addressing identified risks effectively. These plans should outline actionable steps, assign accountability, and establish contingency measures to mitigate the impact of potential risk events. By preemptively devising mitigation strategies, TPMs enhance project resilience and bolster stakeholder confidence in project outcomes.

Furthermore, TPMs should institutionalize the practice of socializing risk logs within project teams and key stakeholders. By disseminating risk information transparently, TPMs foster a culture of risk awareness and collective responsibility for risk mitigation. Additionally, TPMs should collaborate with Designated Risk Owners (DROs) at the program's onset to track and address risks collaboratively. This proactive engagement ensures that risk management remains an integral aspect of project planning and execution.

In essence, effective risk management is not merely a reactive measure but a proactive strategy that underpins project success. By diligently identifying, tracking, and mitigating risks, TPMs safeguard project objectives, enhance stakeholder confidence, and pave the way for seamless project delivery. In doing so, TPMs uphold their pivotal role as architects of resilience and champions of project excellence
Navigating the Role of a Technical Program Manager: Balancing Leadership Dynamics and Strategic Vision
Published: 2024-03-13 20:15:48

As a Technical Program Manager (TPM), one often finds themselves at the intersection of various leadership dynamics within a project team. Among these dynamics, the relationship between the Engineering Manager (EM) and the Product Manager (PM) can be pivotal, sometimes leaving the TPM in the nuanced position of being perceived as a "third wheel." This unique vantage point offers both challenges and opportunities for effective project management and strategic alignment.

In such scenarios, the TPM plays a crucial role in facilitating communication, fostering collaboration, and ensuring alignment between engineering efforts and product objectives. While the EM typically oversees technical execution and the PM focuses on product requirements and market needs, the TPM serves as a bridge, translating between technical complexities and business priorities.

To navigate this role effectively, the TPM must cultivate a deep understanding of both technical and business domains. This involves actively engaging with engineering teams to comprehend project intricacies while also interfacing with product stakeholders to grasp market demands and strategic goals.

Moreover, the TPM must possess strong interpersonal skills to navigate the delicate balance of leadership dynamics. This includes diplomatically addressing potential conflicts or misunderstandings between the EM and PM, while also championing collaboration and synergy within the team.

Furthermore, the TPM should actively seek opportunities to add value beyond traditional project management tasks. By leveraging their holistic perspective, they can contribute to strategic discussions, offering insights that align tech
Automate your command line with EasyKey.shellmenu
Tags: bash, kubectl, git, shell
Published: 2024-03-13 20:01:39

As a developer, I work with many different tools on the command line. That's why I got into the habit of recording everything in a simple shell menu. That's how I came up with [EasyKey.shellmenu](https://github.com/nschlimm/EasyKey.shellmenu). This allows me to easily create shell menus for my tools. I use it for kubectl, Maven and Git. Here is an example:

`source "/path/to/shellmenu.sh"
menuInit "Maven demo menu"
  submenuHead "Life cycle commands:"
     menuItem c "Clean all" "mvn clean:clean"
     menuItem x "Compile" "mvn clean compile" 
     menuItem t "Test" "mvn clean test" 
     menuItem i "Install" "mvn clean install"  
  submenuHead "Also usefull:"
    menuItem d "Analyze dependencies" "mvn dependency:analyze"
    menuItem u "Clean compile force updates" "mvn clean compile -U -DskipTests" 
    menuItem e "Show effective settings" "mvn help:effective-settings"
    menuItem r "Show local repo location" "mvn help:evaluate -Dexpression=settings.localRepository | grep -v '\[INFO\]'" 
    menuItem l "Show global settings file location" showGlobalSettingFile
startMenu`

The snippet creates a simple Maven menu like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sejxg6uvzrdrr68bpxx6.png)

In the repository on Github for [EasyKey.shellmenu](https://github.com/nschlimm/EasyKey.shellmenu) there are two more complex examples of menus for Git and kubectl. Check it out an if you like it please leave me a star for sharing it.
SPRING SECURITY
Tags: springsecurity, jwt, springboot, security
Published: 2024-03-13 19:39:42


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qf9azyo1p5cpa6ipvnpo.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gikwe2qu89ek0aaeefof.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gs4fmljjeonk03vusz85.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czv0k920fgu6htqdacd6.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1trlzjben9y9fp30nz38.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06pq21f7fevbp5js8wte.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jqhb4r5v9pbfivwm0yp.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ghuaowjk6hhpi4kf4vm.PNG)
Zip and Unzip in Python
Tags: python, beginners, programming
Published: 2024-03-13 19:37:44

# Introduction

In the realm of file management, the ability to compress and decompress files and folders is indispensable. Python offers robust functionalities through its `zipfile` module, empowering developers to zip and unzip with ease. In this article, we'll explore the ins and outs of zipping and unzipping files and folders in Python, illuminating the path to efficient file manipulation.

# Index

- Zipping Files
- Unzipping Files
- Zipping Folders
- Unzipping Folders

# Zipping Files

Zipping files in Python is a breeze with the `zipfile` module. Let's dive into a simple example:

```python
import zipfile

# Create a new zip file
with zipfile.ZipFile(file="example.zip", mode="w") as zip_file:
    zip_file.write(filename="file1.txt")
    zip_file.write(filename="file2.txt")

print("Files zipped successfully!")
```

```
Output:
Files zipped successfully!
```

# Unzipping Files

Unzipping files is as straightforward as zipping them. Let's unzip the files we zipped earlier:

```python
import zipfile

# Extract all contents of the zip file
with zipfile.ZipFile(file="example.zip", mode="r") as zip_file:
    zip_file.extractall(path="extracted_files")

print("Files unzipped successfully!")
```

```
Output:
Files unzipped successfully!
```

# Zipping Folders

Zipping entire folders proves immensely useful, especially in scenarios involving multiple files. Here's how you can zip a folder:

```python
import zipfile
import os

# Define the folder to zip
folder_to_zip = "folder_to_zip"

# Create a new zip file
with zipfile.ZipFile(file="folder_example.zip", mode="w") as zip_file:
    for folder_name, subfolders, filenames in os.walk(folder_to_zip):
        for filename in filenames:
            file_path = os.path.join(folder_name, filename)
            zip_file.write(file_path, os.path.relpath(file_path, folder_to_zip))

print("Folder zipped successfully!")
```

```
Output:
Folder zipped successfully!
```

# Unzipping Folders

Unzipping folders preserves the directory structure, facilitating organized file extraction. Let's unzip the folder we zipped previously:

```python
import zipfile

# Extract all contents of the zip file
with zipfile.ZipFile(file="folder_example.zip", mode="r") as zip_file:
    zip_file.extractall(path="extracted_folder")

print("Folder unzipped successfully!")
```

```
Output:
Folder unzipped successfully!
```

# Conclusion

In conclusion, Python's `zipfile` module empowers developers to zip and unzip files and folders effortlessly. Whether you're compressing individual files or entire directories, Python provides a seamless experience, enabling efficient file management.
JavaScript Design Patterns
Tags: javascript, frontend, programming
Published: 2024-03-13 19:35:03

Design patterns are advanced object-oriented solutions, used to recurring problems in software design.

Design patterns have many categorizations, but the most popular one is:

⚡- Creational Design Patterns:
===========================
It deals with object or class creation mechanisms, and it solves design problems when creating objects.
1- Factory Methods
2- Builder
3- Abstract Factory
4- Prototype
5- Singleton

⚡- Structural Design Patterns:
===========================
It assembles objects and classes into a larger structure, making sure that this structure is flexible and efficient, and that if change happens to part of a system it doesn’t affect the system entirely.
1- Adapter
2- Composite
3- Decorator
4- Bridge
5- Flyweight
6- Facade
7- Proxy

⚡- Behavioral Design Patterns:
============================
It’s responsible for improving the communication between disparate objects and classes in a system.
1- Command
2- Interpreter
3- Iterator
4- Memento
5- Observer
6- Template Method
7- Chain of Responsibility
8- Meditor
9- State
10- Strategy
11- Visitor
How do you prepare for PHP interviews? + my list
Published: 2024-03-13 19:27:40

I'd like to hear from php devs(mid/senior) about their experience preparing for tech interviews. How this process looks like most of the time, what services you use, and a list of topics.

During the years, I created my own list of topics to prepare for interviews. Usually, I analyze the job description and try to predict questions as well as highlight my experience from the perspective of the job description.

So, here is my list:

1. New features in php 8.* (last 3 versions)
2. SOLID
3. Ioc Container / Service Container
4. Composition over Inheritance
5. Composition vs Aggregation
6. Polymorphism (for some annoying interviewees :D)
7. DDD, Layered Architecture
8. Design Patterns
9. Dependency Injection
10. Mocks/Stubs
11. %your_framework% new features (almost never asked)
12. Vue 3.0 new features
13. NoSQL / MongoDB
14. RESTful API
15. Testing. PHPUnit/Pest
16. Redis
17. CI/CD
18. RDBMS (MySQL specifically) 
19. Microservices (SOA)
20. Queues (RabbitMQ/Redis)

Please share something about your experience. It would be great if you pointed out the problems you had during preparation or during the interview.