Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joedawson's avatar

Handling 404's with router?

Hello all,

How can I handle 404's with vue-router? I'm using single-file components and have a CategoryView that looks like this:

<template>
    <!-- Template Stuff -->
</template>

<script>
import Product from "../components/Product.vue";

export default {

    name: 'CategoryView',

    props: {
        category: Object
    },

    components: {
        Product
    },

    ready: function() {
        this.getCategory();
    },

    methods: {

        getCategory: function() {
            this.$http.get('/api/categories/' + this.$route.params.category + '?include=products', function(category) {
                this.$set('category', category.data);
            }).error(function(resp) {
                console.log('404\'d');
            });
        }

    }

}
</script>

Currently, any top-level routes that do not exist are returning a NotFoundView which I do like so:

router.map({
    '/':                        { component: HomeView },
    '/category/:category':      { component: CategoryView },
    '*':                        { component: NotFoundView }
});

How can I use the same view when in this case, a category does not exist?

I hope I'm making sense!

0 likes
1 reply
kfirba's avatar

@JoeDawson Hey.

The callback defined in .error() takes 3 arguments: data, status and xhr. That means you can just do something like:

getCategory: function() {
    this.$http.get('/api/categories/' + this.$route.params.category + '?include=products', function(category) {
        this.$set('category', category.data);
    }).error(function(resp, status) {
    if (status == 404) {
        return this.$route.router.go('*')
    }
        console.log('404\'d');
    });
}

As it currently stands the vue-router package has no interceptors (well there are interceptors in the develop branch) so you can't define a global hook where you can always catch a 404 responses and redirect to the not found page, so you have to manually do it now.

By the way, a word of advice, define yourcategory variable in the data of your VM even if it means setting it to null:

data: function () {
    return {
        category: null
    }
}

Please or to participate in this conversation.