整体概览
先来看整体的结构图:(广东人:丢你老味)
具体操作
先在pojo层定义一个异常的实体类ErrorResponse,在这里我们可以自定义我们想要的对象,比如这里我想要返回状态码,错误码以及错误信息:
@Data
public class ErrorResponse {
private int status;
private String errorCode;
private String message;
public ErrorResponse(int status, String errorCode, String message) {
this.status = status;
this.errorCode = errorCode;
this.message = message;
}
public ErrorResponse(String errorCode, String message) {
this.errorCode = errorCode;
this.message = message;
}
}
在exception文件夹定义一个异常类ProductNotfoundException:
@EqualsAndHashCode(callSuper = true)
@Data
public class ProductNotfoundException extends RuntimeException {
private String errorCode;
public ProductNotfoundException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
}
在controller层,定义ProductExceptionController类。在这里我们写入返回的状态码HttpStatus:
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value = ProductNotfoundException.class)
@ResponseBody
public ResponseEntity<ErrorResponse> exception(ProductNotfoundException exception) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), exception.getErrorCode(), exception.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.OK);
}
}
再定义一个应用异常的服务控制类ProductServiceController。在这里我们写入我们自定义的错误码--errorCode,错误信息--message:
@RestController
public class ProductServiceController {
@PutMapping(value = "/products/{id}")
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
if(!productRepo.containsKey(id)) throw new ProductNotfoundException("40004", "Not found qaq");
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("product update success", HttpStatus.OK);
}
}
结果展示
用postman调试接口,会得到一个异常信息对象。会了吗,番薯(在广东番薯是大帅哥的意思)