全局的异常处理

全局的异常处理

ResponseEntity

它是Spring提供的一个类,它内部封装了状态码,请求头,请求体等信息,用户可以根据自己的需要修改状态码、请求体的信息。ResponseEntity中的泛型用于指定请求体的类型,它的请求体和@ResponseBody的作用完全一致,并且ResponseEntity的优先级要高于@ResponseBody,即:如果返回值是ResponseEntity,即使存在ResponseBody或者@RestController注解,也默认不会生效,而是使用ResponseEntity。

HttpStatus

这是Spring提供的一个枚举类,其遵循RESTful风格封装了大量了响应状态码。详见org.springframework.http.HttpStatus;

如何使用ResponseEntity

//使用构造参数构建
new ResponseEntity<String>("return info",HttpStatus.BAD_REQUEST);
//使用构造参数构建
new ResponseEntity<JavaBean>(javaBean,HttpStatus.BAD_REQUEST);

使用status设置响应码,body指定响应头

//使用status方法和body方法
ResponseEntity.status(HttpStatus.CREATED).body(javaBean);
//使用status方法和body方法
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);

另外还可以设置响应头:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");

    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
}

如果只是返回一个状态码为200的内容,可以简写为:

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello World!");
}

最后强调一下:BodyBuilder.body()返回ResponseEntity ,所以需要最后调用。

使用HttpServletResponse response

Spring同样支持我们使用HttpServletResponse对象来操作请求头和请求体,用法如下:

@GetMapping("/manual")
void manual(HttpServletResponse response) throws IOException {
    response.setHeader("Custom-Header", "foo");
    response.setStatus(200);
    response.getWriter().println("Hello World!");
}

既然spring已经提供底层实现的抽象和附件功能,我们不建议直接操作response。

ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
ResponseEntity.ok(list);
ResponseEntity.badRequest().build();
ResponseEntity.notFound().build();

上述是比较简单的两种用法,分别是500和200、400、404

转自:https://www.cnblogs.com/zhangruifeng/p/13260542.html

原文地址:https://www.cnblogs.com/ed1s0n/p/14261806.html