小编and*_*ero的帖子

TypeScript 中的可选参数可以为 null 吗?

根据这篇文章,当在 TypeScript 中启用严格的空值检查时,除非联合明确允许,否则您不能分配null或分配undefined给变量。

// required value
let req: string;
req = "Something";  // OK
req = null;      // Error
req = undefined; // Error

// nullable value
let nbl: string | null;
nbl = "Something";  // OK
nbl = null;      // OK
nbl = undefined; // Error
Run Code Online (Sandbox Code Playgroud)

但是在 TypeScript 中null允许在可选值中使用吗?

// optional value
let opt?: string; // (actually invalid, as optional types cannot be used for variable declarations, but that's …
Run Code Online (Sandbox Code Playgroud)

nullable undefined optional typescript

37
推荐指数
1
解决办法
2万
查看次数

如何识别配置文件的语法及其等效的 Markdown 语言标识符?

介绍

在配置软件包时,您会遇到各种使用各种不同语法的配置文件。

除了.json.xml.yml.properties之外,下面是一些我无法找到其名称的常见语法示例。

空白分隔

# comment
value11 value12
value21 value22 value23 value24
Run Code Online (Sandbox Code Playgroud)

您可能会在“/etc/hosts”中找到此语法,并且还嵌入在 Apache2 配置标记(例如<VirtualHost>)下等位置。似乎经常用于列出别名。

空格分隔和缩进嵌套

Key1 value1 value2 value3
    Key2 value4 value5
    Key3 value6

Key4 value7
    Key5 value8
Run Code Online (Sandbox Code Playgroud)

您可以在“~/.ssh/config”中找到此语法。嵌套将嵌套值与父值联系起来。看起来像没有符号的 yaml。

Apache2配置

您可以使用空格分隔值,也可以使用 XML 标签来分隔配置块。

# Ensure that Apache listens on port 80
Listen 80
<VirtualHost *:80>
    DocumentRoot "/www/example1"
    ServerName www.example.com

    # Other directives here
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

鸽舍配置

您可以使用特定关键字和花括号开始一个块,然后像在文件中一样使用=赋值.properties

protocol imap {
  ssl_cert = </etc/ssl/certs/imap.pem
  ssl_key = …
Run Code Online (Sandbox Code Playgroud)

syntax markdown syntax-highlighting configuration-files

12
推荐指数
1
解决办法
6561
查看次数

为什么可以在主线程上运行 Kotlin 协程?

我无法理解为什么 这段代码可以正常工作:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    launch(Dispatchers.Main) {
        log("A")
    }

    log("B")
}
Run Code Online (Sandbox Code Playgroud)

应该B先输出,然后输出A

这行得通吗,因为主线程已经由协程控制了?或者协程 API 是否以某种方式神奇地将代码注入到主线程中?

coroutine kotlin kotlin-coroutines android-multithreading

12
推荐指数
2
解决办法
1万
查看次数

Spring @ControllerAdvice vs ErrorController

在我的REST服务应用程序中,我计划创建一个@ControllerAdvice类来捕获控制器抛出异常并根据错误类型返回ResponseEntity对象.

但我已经设置了一个@RestController扩展ErrorController来捕获"whitelabel"错误.

这两个人是否以任何方式干涉?在哪种情况下,在设置@ControllerAdvice时会调用ErrorController?

编辑ErrorController代码按要求

@RestController
public class ControllerCustomError implements ErrorController{

    //error json object
    public class ErrorJson {

        public Integer status;
        public String error;
        public String message;
        public String timeStamp;
        public String trace;

        public ErrorJson(int status, Map<String, Object> errorAttributes) {
            this.status = status;
            this.error = (String) errorAttributes.get("error");
            this.message = (String) errorAttributes.get("message");
            this.timeStamp = errorAttributes.get("timestamp").toString();
            this.trace = (String) errorAttributes.get("trace");
        }

    }

    private static final String PATH = "/error";

    @Value("${hybus.error.stacktrace.include}")
    private boolean includeStackTrace = false;

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = PATH)
    ErrorJson …
Run Code Online (Sandbox Code Playgroud)

error-handling spring exception spring-mvc spring-boot

9
推荐指数
1
解决办法
1435
查看次数

在 Spring Boot 中的异常处理期间保留自定义 MDC 属性

简短版本(有足够的细节)

如何保留在实现的doFilter()方法中添加的 MDC 属性javax.servlet.Filter...

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        MDC.put("token", MyToken.random()); // add the MDC attribute related to the current request processing
        chain.doFilter(request, response); // send the request to other filters and the Controller
    } finally {
        MDC.clear(); // MDC attribute must be removed so future tasks executed on the same thread would not log invalid information
    }
}
Run Code Online (Sandbox Code Playgroud)

... 在异常处理期间,如果异常发生在另一个过滤器或控制器中(对 的调用chain.doFilter(...))。

当前,如果发生异常:将执行 finally 块,清除 …

java error-handling spring mdc spring-boot

9
推荐指数
1
解决办法
1544
查看次数

线程在线程池中休眠

假设我们有一个线程池数量有限的线程。

Executor executor = Executors.newFixedThreadPool(3);
Run Code Online (Sandbox Code Playgroud)

现在假设其中一项活动任务必须休眠 3 秒(无论出于何种原因)。

executor.execute(() -> {
    try {
        Thread.sleep(3000L);
    } catch (InterruptedException ignore) {}
});
Run Code Online (Sandbox Code Playgroud)

我们如何实现这样一个线程池,当一个任务休眠(或等待监视器/条件)时,线程1可以有效地用于运行另一个任务?

1 通过螺纹我的意思不是“物理” Java线程,因为当线程处于睡眠状态,这将是不可能的。我的意思是,线程池有一个抽象的实现,它实际上似乎允许一个线程在睡眠期间运行另一个任务。关键是总是有 N 个同时运行(非休眠)的任务。

有点类似于监视器处理对关键区域的访问的方式:

  • 如果一个线程等待一个资源,该资源可以被另一个线程使用。
  • 如果线程得到通知,它就会被放入等待集中以(重新)获得对该资源的访问权。

java performance multithreading threadpool threadpoolexecutor

9
推荐指数
1
解决办法
2856
查看次数

在功能组件中反应 URI 参数

从功能性 React 组件读取 URI 参数的正确方法是什么?

在 JavaScript 中,如果组件是 a 的直接子组件Switch,我们可以这样做:

function MyComponent(props) {
    const query = props.location.search;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果组件不是 a 的直接子Switch级,我们可以使用一个类:

class MyComponent extends Component<RouteComponentProps> {
    render() {
        const query = this.props.location.search;
        // ...
    }
}

export default withRouter(MyComponent);
Run Code Online (Sandbox Code Playgroud)

严格的 TypeScript 中的功能组件怎么样?

我们希望location属性(以及任何其他属性,如果有更多)可用并由 some interfaceor预定义type,但由 React 提供,而不是组件的用户。一个丑陋的黑客是自己定义接口,然后期望它实际上是那样的。

url url-parameters typescript reactjs react-router

8
推荐指数
4
解决办法
2万
查看次数

Promise.then(a,b)和Promise.then(a).catch(b)一样吗?

有什么区别

因为这两种JavaScript表达式总是产生相同的结果,无论是内容和状态myPromise和功能的实现ab

除了代码可读性之外,我是否应该更喜欢使用一个而不是另一个?

javascript promise es6-promise

7
推荐指数
2
解决办法
205
查看次数

Tomcat NioEndpoint - 运行套接字处理器时出错

在 Spring Boot 生产应用中,偶尔会抛出以下异常:

o.a.t.u.n.NioEndpoint : Error running socket processor

java.util.NoSuchElementException: No value present
        at java.util.Optional.get(Optional.java:148) ~[?:?]
        at sun.security.ssl.ServerHello$T13ServerHelloProducer.produce(ServerHello.java:547) ~[?:?]
        at sun.security.ssl.SSLHandshake.produce(SSLHandshake.java:436) ~[?:?]
        at sun.security.ssl.ClientHello$T13ClientHelloConsumer.goServerHello(ClientHello.java:1234) ~[?:?]
        at sun.security.ssl.ClientHello$T13ClientHelloConsumer.consume(ClientHello.java:1170) ~[?:?]
        at sun.security.ssl.ClientHello$ClientHelloConsumer.onClientHello(ClientHello.java:852) ~[?:?]
        at sun.security.ssl.ClientHello$ClientHelloConsumer.consume(ClientHello.java:813) ~[?:?]
        at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) ~[?:?]
        at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443) ~[?:?]
        at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1061) ~[?:?]
        at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1048) ~[?:?]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
        at sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:995) ~[?:?]
        at org.apache.tomcat.util.net.SecureNioChannel.tasks(SecureNioChannel.java:443) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at org.apache.tomcat.util.net.SecureNioChannel.handshakeUnwrap(SecureNioChannel.java:507) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at org.apache.tomcat.util.net.SecureNioChannel.handshake(SecureNioChannel.java:238) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1616) [tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.31.jar!/:9.0.31]
        at java.lang.Thread.run(Thread.java:834) …
Run Code Online (Sandbox Code Playgroud)

tomcat runtime-error spring-boot

7
推荐指数
1
解决办法
5796
查看次数

在功能性 React 组件中定义处理程序的正确方法?

据我所知,在 JavaScript 中定义函数有三种方式。

1. 声明

function handleEvent(e) {}
Run Code Online (Sandbox Code Playgroud)

2. 分配

var handleEvent = function(e) {}
Run Code Online (Sandbox Code Playgroud)

3. 箭头

var handleEvent = (e) => {}
Run Code Online (Sandbox Code Playgroud)

我一直在寻找有关这些选项中哪个是在功能性 React 组件中声明处理程序的首选方式的信息。我发现的所有文章都讨论了类组件、绑定等。但是随着新Hooks 的出现,在函数内部也必须有定义它们的标准。(毕竟,无论如何,功能组件一直存在。)

考虑以下组件,它声明了三个处理程序,它们是您在 React 组件中可能需要的不同行为的示例。

function NameForm(props) {
    const [inputName, setInputName] = useState("");

    useEffect(() => setInputName(props.initialValue), [props.initialValue]);

    const handleInputChange = function(event) {
        setInputName(event.target.value);
    };

    const resetForm = function() {
        setInputName(props.initialValue);
        props.onReset();
    };

    const handleFormSubmit = function(event) {
        event.preventDefault();
        props.onSubmit(inputName);
        resetForm();
    };

    /* React-Bootstrap simple form example using these handlers. */
    return (
        <Form …
Run Code Online (Sandbox Code Playgroud)

javascript function nested-function reactjs react-hooks

6
推荐指数
2
解决办法
2803
查看次数