处理未定义网址的错误

时间:2018-11-23 18:18:36

标签: javascript reactjs error-handling routing

我的前端日志中充满了这些错误。 当我碰到任何未定义的地址时,我在终端中(不是在浏览器中的vscode中)得到了这个。 主要问题是我不确定如何处理由未定义的URL引起的错误。例如,在这里我知道import oscP5.*; OscP5 oscP5; float value; void setup(){ size(400, 400, P3D); rectMode(CENTER); oscP5 = new OscP5(this, 60000); } void oscEvent(OscMessage theOscMessage){ if (theOscMessage.checkAddrPattern("/ATT")){ value = theOscMessage.get(0).floatValue(); } } void draw(){ background(0); noStroke(); fill(255); float r = second()/10; rotateZ(r); rect(width/2, height/2, value, value); } 是未定义的,并且不存在,但是我不知道如何阻止js尝试映射此未定义的URL。

/ca/en/category

这是我如何建立地址(针对类别):

    error: {
  "requestedPath": "/ca/en/category", (or any other unefined address)
  "errorMessage": "Cannot read property 'map' of undefined",
  "clientIp": "::1"
}
TypeError: Cannot read property 'map' of undefined
    at Chrome.module.exports../src/components/Chrome.tsx.Chrome.render (...\dist\server.js:518:916)
    at processChild (...\node_modules\react-dom\cjs\react-dom-server.node.development.js:2207:18)
    at resolve (...\node_modules\react-dom\cjs\react-dom-server.node.development.js:2064:5)
    at ReactDOMServerRenderer.render (...\node_modules\react-dom\cjs\react-dom-server.node.development.js:2383:22)
    at ReactDOMServerRenderer.read (...\react-dom\cjs\react-dom-server.node.development.js:2357:19)
    at Object.renderToString (...\node_modules\react-dom\cjs\react-dom-server.node.development.js:2729:25)
    at...\dist\server.js:4346:69
    at step (...\node_modules\tslib\tslib.js:133:27)
    at Object.next (...\node_modules\tslib\tslib.js:114:57)
    at fulfilled (...e\node_modules\tslib\tslib.js:104:62)

我有一个server.js文件,在518行中,我有:

    if (pathname.startsWith('/category/')) {
        const cat = menu.find(({ slug }) => pathname.startsWith('/category/' + slug));
        if (cat) {
            leftBar = cat.subcategories.map(({ name, productLines, slug: subSlug }) => ({
                title: name,
                path: `/category/${cat.slug}/${subSlug}`,
                links: productLines.map(({ name, slug }) => ({
                    title: name,
                    path: `/category/${cat.slug}/${subSlug}/${slug}`,
                })),
            }));
            leftBarTitle = cat.name;
        }
    }

我认为终端中不应出现这样的错误,但是我不确定如何处理。

3 个答案:

答案 0 :(得分:0)

只需尝试以下代码,看看您尝试在哪里映射undefined对象

if(!cat.subcategories) console.log('not exist but i try to map')

cat.subcategories.map(({ name, productLines, slug: subSlug }) => {  
    if(!productLines) console.log('not exist but i try to map')

})`

答案 1 :(得分:0)

您可以通过以下方式进行验证:

if(!cat.subcategories) return

答案 2 :(得分:0)

在渲染中,您始终需要返回一些内容,因此这就是我解决问题的方式:

            if (cat) {....
        } else {
            return <Redirect to="/" />;

这样做,它将把我重定向到一个地址,并且不再给我Nothing was returned from render.