我正在为一个大学项目编写一个简单的库 API。我有一个包含书籍的数据库,每个数据库都有自己的 ID。我正在使用 Spring Boot 来制作服务。我有一个BookRepositorywhich extendsJpaRepository<Book, Long>和一个服务实现。
@Service
public class BookServiceImpl implements BookService{
@Autowired
private BookRepository bookRepository;
@Async
@Override
public void delete (Long id){
bookRepository.delete(id);
}
}
Run Code Online (Sandbox Code Playgroud)
稍后,REST 控制器处理请求:
@RestController
public class BookServiceController{
@Autowired
private BookService bookService;
@RequestMapping(value="books/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Book> deleteBook (@PathVariable("id") Long id){
bookService.delete(id);
return new ResponseEntity<Book>(HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我要删除不在数据库中的 Book(例如 ID 为 123),则会抛出 EmptyResultDataAccessException。
我的问题是,我如何以及在哪里处理异常,以及如何避免以这种方式投射 NullPointerException?
提前致谢。
我在这里可能遗漏了一些明显的东西,但我似乎无法在我的 FileStream 读取中设置编码。这是代码:
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
using (fs)
{
byte[] buffer = new byte[chunk];
fs.Seek(chunk, SeekOrigin.Begin);
int bytesRead = fs.Read(buffer, 0, chunk);
while (bytesRead > 0)
{
ProcessChunk(buffer, bytesRead, database, id);
bytesRead = fs.Read(buffer, 0, chunk);
}
}
fs.Close();
Run Code Online (Sandbox Code Playgroud)
ProcessChunk 将读取的值保存到对象,然后将其序列化为 XML,但读取的字符显示错误。编码需要是 1250。我还没有看到将编码添加到 FileStream 的选项。我在这里缺少什么?