小编Chr*_*onn的帖子

如何捕获 fetch api 请求时的错误?

我正在使用 fetch api 发送请求,并根据结果正确或包含错误采取行动。

我的服务代码:

LoginUser(user: User) {
    return fetch("http://localhost:8080/login", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(user)
    });
  }
Run Code Online (Sandbox Code Playgroud)

then-catch调用上面代码的代码是:

async loginUser() {
  let response = await this._service.LoginUser(this.user)
  .then(response => {return response.json()})
  .then(response => {this._router.navigate(['/mainpage'])})
  .catch(error => {alert(error)});
 }
Run Code Online (Sandbox Code Playgroud)

响应是否带有代码 500 内部服务器错误,仍然重定向到/mainpage并且无法识别该错误。我该如何解决这个问题?

javascript fetch typescript fetch-api angular

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

如何在每次 junit 测试后清理 h2 db?

我正在进行 junit 测试,在每个测试用例之前添加一些用户。代码是:

@BeforeEach
    void setUp() {
        saveUser();
        saveEntry();
    }
    
    @Test
    void saveUser() {
        User user = new User();
        user.setUserId(null);
        user.setUsername("John");
        user.setEmail("john@foo.com");
        user.setPassword("password");
        userService.saveUser(user);
    }

    @Test
    void saveEntry() {
        Entry entry = new Entry();
        entry.setText("test text");
        entry.setUserId(1L);
        entryService.saveEntry(entry);
    }
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用服务层中的方法来创建条目和用户。如果我一项一项地运行测试,就没有问题。但是当我运行所有测试时,数据库不会返回 1 个项目,而是返回多个项目,因此会发生异常。

我需要在每次测试后使用 @AfterEach 注释清理 h2 db,但我的代码中没有并删除要调用的方法。如何清理 H2 数据库?

java junit spring unit-testing h2

3
推荐指数
1
解决办法
5194
查看次数

Java hibernate 找不到布尔值的验证器

我有一个服务方法,它尝试使用store()休眠方法添加一个对象。get 方法适用于此 DAO 和服务类,而添加不起作用。在控制台中没有错误。

UrlWhiteListDaoImpl urlDao;

MapperFacade mapper;

@Autowired
public UrlWhiteListingServiceImpl(UrlWhiteListDao urlWhiteListDao, MapperFacade mapper, UrlWhiteListDaoImpl urlDao) {
    this.urlDao = urlDao;
    this.urlWhiteListDao = urlWhiteListDao;
    this.mapper = mapper;
}

@Override
public UrlWhiteListDto addUrlWhiteListItem(UrlWhiteListDto urlWhiteListDto) throws Exception {
    String domainUrlToBeAdded = parseUrl(urlWhiteListDto.getDomain());
    if (isDomainExistbyName(domainUrlToBeAdded)) {
        throw new Exception("Already existed domain is tried to be added");
    }
    UrlWhitelist urlModel = mapper.map(urlWhiteListDto,UrlWhitelist.class);
    urlDao.store(urlModel);
    return urlWhiteListDto;
Run Code Online (Sandbox Code Playgroud)

}

我的模型类是:

@Entity
@Table(name = UrlWhitelist.TABLE_NAME)
public class UrlWhitelist implements EntityBean { 

    public static final String TABLE_NAME = …
Run Code Online (Sandbox Code Playgroud)

java validation spring annotations hibernate

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

如何在Java中根据多个参数过滤列表中的数据?

我有一个GroupOffices列表

List<GroupOffice> officesOfTheGroup;
Run Code Online (Sandbox Code Playgroud)

我想搜索id是否等于groupOffice.getId(长值),但标签为groupOffice.getLabel(字符串),并将其分配给布尔值。下面的代码运行良好,但是有没有比使用for循环遍历所有项目更好的方法了?

 public GroupOfficeDto saveGroupOffice(GroupOfficeDto groupOfficeDto) {     
            List<GroupOffice> officesOfTheGroup = //some list from db..
            for (GroupOffice go : officesOfTheGroup) {
                if ((!go.getId().equals(groupOfficeDto.getId())) && go.getLabel().equals(groupOfficeDto.getLabel())) {
                    return groupOfficeDto;
                }
        return null:
}
Run Code Online (Sandbox Code Playgroud)

或者如何使用流?如果是这样,使用流是更好的方法吗?

注意:我正在使用Java8

java list stream java-8 java-stream

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

如何使用 java -version 命令查看brew安装的java?

我已经使用以下命令使用自制程序安装了 java open jdk 最新版本:

brew install openjdk
Run Code Online (Sandbox Code Playgroud)

我尝试使用命令检查已安装的版本

/usr/libexec/java_home -V
Run Code Online (Sandbox Code Playgroud)

什么也没有显示。

该命令java -version还显示:

No Java runtime present, requesting install
Run Code Online (Sandbox Code Playgroud)

我的java在哪里?如何查看已安装的版本并使用它并使用java -version命令查看它

java bash homebrew homebrew-cask

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

如果存在Java可选,如何执行某些操作或抛出异常?

我想做的是,如果存在客户,则更新客户,但如果没有客户,则抛出异常。但我找不到正确的流函数来做到这一点。我怎样才能做到这一点?

public Customer update(Customer customer) throws Exception {
        Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
        customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
        throw new Exception("customer not found"));
    }
Run Code Online (Sandbox Code Playgroud)

我无法返回来自保存函数的值,因为它说它是 void 方法并且不期望返回值。

java spring exception spring-boot option-type

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

How to assign multiple value to an enum in Typescript?

How to assign multiple value to an enum in typescript ? my enum is:

export enum TaxabilityType {
  Yes = 'TAXABLE',
  No = 'NON_TAXABLE',
  Unknown = 'MAYBE'
}
Run Code Online (Sandbox Code Playgroud)

But I do not need 'Unknown' and for the value 'MAYBE' I want 'No' so I need something like:

  export enum TaxabilityType {
      Yes = 'TAXABLE',
      No = 'NON_TAXABLE' || 'MAYBE'

    }
Run Code Online (Sandbox Code Playgroud)

How can I achieve it ?

html javascript typescript angular

0
推荐指数
2
解决办法
90
查看次数

如何允许将 vue.js 获取到后端的 cors 策略?

我有一个前端代码,它正在向后端发出请求

(前端在 localhost:8081 上工作,请求将转到 localhost:8080)

前端代码为:

<script lang="ts">import 'vue-material/dist/vue-material.css'
export default {
  tasks: [],
  data () {
    return {
    }
  },
  methods: {
       BLABLA
  },
  created () {
    fetch('http://localhost:8080/getTasks')
      .then(response => {
        return response.json()
      })
      .then(tasks => {
        this.tasks = tasks
      })
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

和后端控制器是:

import com.example.dto.TaskDto;
import com.example.model.Task;
import com.example.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class TodoListController {

    @Autowired
    TaskService taskService; …
Run Code Online (Sandbox Code Playgroud)

javascript spring http-headers cors vue.js

0
推荐指数
1
解决办法
60
查看次数