Skip to content

Commit cb2e312

Browse files
committed
update all errors are returned as json response
1 parent 7a32497 commit cb2e312

File tree

4 files changed

+76
-69
lines changed

4 files changed

+76
-69
lines changed

arxiv/arxiv_api.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@ func parseXML(xmlStr string) Feed {
4343
return result
4444
}
4545

46-
func SearchPapers(params map[string]string) Feed {
46+
func SearchPapers(params map[string]string) (Feed, error) {
4747
// define api url
4848
u, err := url.Parse("http://export.arxiv.org/api/query")
4949
if err != nil {
50-
log.Fatal(err)
50+
return Feed{}, err
5151
}
5252

5353
// construct query string
@@ -60,15 +60,15 @@ func SearchPapers(params map[string]string) Feed {
6060
// send the request
6161
resp, err := http.Get(u.String())
6262
if err != nil {
63-
log.Fatal(err)
63+
return Feed{}, err
6464
}
6565

6666
// parse result xml
6767
xmlBytes, err := ioutil.ReadAll(resp.Body)
6868
if err != nil {
69-
log.Fatal(err)
69+
return Feed{}, err
7070
}
7171
xmlObj := parseXML(string(xmlBytes))
7272

73-
return xmlObj
73+
return xmlObj, nil
7474
}

controller/errors.go

+6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package controller
22

33
import (
4+
"fmt"
45
"net/http"
56

67
"github.com/labstack/echo"
@@ -11,6 +12,11 @@ type APIError struct {
1112
Message string `json:"message"`
1213
}
1314

15+
func newErrorWithMsg(err error, msg string) error {
16+
msg += "(" + err.Error() + ")"
17+
return fmt.Errorf(msg)
18+
}
19+
1420
// error handler which returns errors in json format
1521
func JSONErrorHandler(err error, c echo.Context) {
1622
code := http.StatusInternalServerError

controller/paper.go

+59-40
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,41 @@ import (
1919
"github.com/raahii/arxiv-equations/latex"
2020
)
2121

22-
func readFile(path string) string {
22+
func readFile(path string) (string, error) {
2323
str, err := ioutil.ReadFile(path)
2424
if err != nil {
25-
log.Fatal(err)
25+
return "", err
2626
}
2727

28-
return string(str)
28+
return string(str), nil
2929
}
3030

31-
func readAllSources(mainLatexPath string, basePath string) string {
31+
func readAllSources(mainLatexPath string, basePath string) (string, error) {
3232
// read all \input or \include tag and
3333
// obtain all related sources concatenated string
34-
source := readFile(mainLatexPath)
34+
source, err := readFile(mainLatexPath)
35+
if err != nil {
36+
return "", err
37+
}
38+
3539
source = latex.RemoveComment(source)
3640
source = strings.Replace(source, "*{", "{", -1)
3741
source = strings.Replace(source, "*}", "}", -1)
3842

39-
re := regexp.MustCompile(`\\(input|include)\{(.*?)\}`)
43+
re, err := regexp.Compile(`\\(input|include)\{(.*?)\}`)
44+
if err != nil {
45+
return "", err
46+
}
4047

4148
resolveInputTag := func(s string) string {
4249
path := re.FindStringSubmatch(s)[2]
4350
if filepath.Ext(path) == "" {
4451
path = path + ".tex"
4552
}
46-
_source := readFile(filepath.Join(basePath, path))
53+
_source, err := readFile(filepath.Join(basePath, path))
54+
if err != nil {
55+
panic(err)
56+
}
4757
_source = latex.RemoveComment(_source)
4858
return _source
4959
}
@@ -56,25 +66,28 @@ func readAllSources(mainLatexPath string, basePath string) string {
5666
source = re.ReplaceAllStringFunc(source, resolveInputTag)
5767
}
5868

59-
return source
69+
return source, nil
6070
}
6171

62-
func findSourceRoot(paths []string) string {
72+
func findSourceRoot(paths []string) (string, error) {
6373
// search source which includes '\documentclass'
6474
found := false
6575
mainPath := ""
6676
for _, path := range paths {
67-
source := readFile(path)
77+
source, err := readFile(path)
78+
if err != nil {
79+
return "", err
80+
}
6881
source = latex.RemoveComment(source)
6982
if strings.Contains(source, `\documentclass`) {
7083
found = true
7184
mainPath = path
7285
}
7386
}
7487
if !found {
75-
log.Fatal(fmt.Errorf("Main latex source is not found"))
88+
return "", fmt.Errorf("Latex file is not found")
7689
}
77-
return mainPath
90+
return mainPath, nil
7891
}
7992

8093
func extractArxivId(arxivUrl string) string {
@@ -83,54 +96,57 @@ func extractArxivId(arxivUrl string) string {
8396
return strs[len(strs)-1]
8497
}
8598

86-
func (paper *Paper) readLatexSource(path string) {
99+
func (paper *Paper) readLatexSource(path string) error {
87100
var err error
88101

89102
// download tarball
90-
log.Println("Downloading tarball", paper.TarballUrl)
91103
tarballPath := filepath.Join(path, paper.ArxivId+".tar.gz")
92104
err = arxiv.DownloadTarball(paper.TarballUrl, tarballPath)
93105
if err != nil {
94-
log.Fatal(err)
106+
return newErrorWithMsg(err, "Error occured during downloading tarball")
95107
}
96108

97109
// decompress tarball
98110
sourcePath := filepath.Join(path, paper.ArxivId)
99-
log.Println("Decompressing tarball", sourcePath)
100111
os.Mkdir(sourcePath, 0777)
101112

102113
err = exec.Command("tar", "-xvzf", tarballPath, "-C", sourcePath).Run()
103114
if err != nil {
104-
log.Fatal(err)
115+
return newErrorWithMsg(err, "Error occured during decompressing tarball.")
105116
}
106117

107118
// list all *.tex
108-
log.Println("Processing tex files")
109119
pattern := filepath.Join(sourcePath, "**/*.tex")
110120
files, err := zglob.Glob(pattern)
111121
if err != nil {
112-
log.Fatal(err)
122+
return newErrorWithMsg(err, "Error occurred during processing tex files(1)")
113123
}
114124

115125
// find root latex source file
116-
rootFile := findSourceRoot(files)
126+
rootFile, err := findSourceRoot(files)
127+
if err != nil {
128+
return newErrorWithMsg(err, "Error occurred during processing tex files(2)")
129+
}
117130

118131
// obtain all latex source
119-
allSource := readAllSources(rootFile, sourcePath)
132+
allSource, err := readAllSources(rootFile, sourcePath)
133+
if err != nil {
134+
return newErrorWithMsg(err, "Error occurred during processing tex files(3)")
135+
}
120136

121137
// obtain macros
122138
log.Println("Extracting macros")
123139
macros, err := latex.FindMacros(allSource)
124140
if err != nil {
125-
log.Fatal(err)
141+
return newErrorWithMsg(err, "Error occurred during extracting macros")
126142
}
127143
paper.Macros = strings.Join(macros, "\n")
128144

129145
// obtain equations
130146
log.Println("Extracting equations")
131147
equationStrs, err := latex.FindEquations(allSource)
132148
if err != nil {
133-
log.Fatal(err)
149+
return newErrorWithMsg(err, "Error occurred during extracting equations")
134150
}
135151
equations := []Equation{}
136152
for _, str := range equationStrs {
@@ -142,21 +158,30 @@ func (paper *Paper) readLatexSource(path string) {
142158

143159
// remove tarball
144160
if err := os.Remove(tarballPath); err != nil {
145-
log.Fatal(err)
161+
return err
146162
}
147163
if err := os.RemoveAll(sourcePath); err != nil {
148-
log.Fatal(err)
164+
return err
149165
}
166+
167+
return nil
150168
}
151169

152170
func FetchPaper(arxivId string) (Paper, error) {
153-
// search papers
171+
// search paper from id
154172
params := map[string]string{
155173
"id_list": arxivId,
156174
}
157-
apiResult := arxiv.SearchPapers(params)
158-
// error handling is needed
175+
apiResult, err := arxiv.SearchPapers(params)
176+
if err != nil {
177+
return Paper{}, err
178+
}
179+
159180
apiEntry := apiResult.Entries[0]
181+
if apiEntry.Title == "Error" {
182+
err := fmt.Errorf(apiEntry.Summary)
183+
return Paper{}, err
184+
}
160185

161186
// convert api result to paper entity
162187
authors := []Author{} // for now, authors are just a string
@@ -190,13 +215,10 @@ func FetchPaper(arxivId string) (Paper, error) {
190215

191216
func FindPaperFromUrl() echo.HandlerFunc {
192217
return func(c echo.Context) error {
193-
err := fmt.Errorf("test error")
194-
return err
195-
196218
// obtain url from GET parameters
197219
url := c.QueryParam("url")
198220
if url == "" {
199-
log.Fatal(fmt.Errorf("Invalid parameters"))
221+
fmt.Errorf("Invalid parameters")
200222
}
201223

202224
// remove version number from url
@@ -207,29 +229,26 @@ func FindPaperFromUrl() echo.HandlerFunc {
207229
arxivId := extractArxivId(url)
208230

209231
// find the paper
210-
database := db.GetConnection()
211232
paper := Paper{}
233+
database := db.GetConnection()
212234
if database.Where("arxiv_id = ?", arxivId).First(&paper).RecordNotFound() {
213-
// if the paper doesn't exist in the database
214-
215-
// fetch the paper
216-
paper, err := FetchPaper(arxivId)
235+
// if the paper doesn't exist in the database, fetch the paper
236+
_paper, err := FetchPaper(arxivId)
217237
if err != nil {
218238
return err
219239
}
240+
paper = _paper
220241

221242
// extract macros and equations
222243
vars := config.Config.Variables
223244
tarballDir := vars["tarballDir"]
224245
paper.readLatexSource(tarballDir)
225246

226247
if dbc := database.Create(&paper); dbc.Error != nil {
227-
log.Fatal(dbc.Error)
248+
return dbc.Error
228249
}
229250
} else {
230251
database.Model(&paper).Related(&paper.Equations).Related(&paper.Authors)
231-
// tarballDir := "tarballs"
232-
// paper.readLatexSource(tarballDir)
233252
}
234253

235254
// add macro to process fine for unsupported command in mathjax

latex/latex.go

+6-24
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package latex
22

33
import (
44
"fmt"
5-
"io/ioutil"
6-
"log"
75
"regexp"
86
"strings"
97
)
@@ -22,12 +20,15 @@ func RemoveComment(str string) string {
2220
return str
2321
}
2422

25-
func RemoveTags(str string, tags []string) string {
23+
func RemoveTags(str string, tags []string) (string, error) {
2624
tagsStr := strings.Join(tags, "|")
2725
pattern := fmt.Sprintf(`\\(%s)(\{.*\})?(\n)?`, tagsStr)
28-
re := regexp.MustCompile(pattern)
26+
re, err := regexp.Compile(pattern)
27+
if err != nil {
28+
return "", err
29+
}
2930

30-
return re.ReplaceAllString(str, "")
31+
return re.ReplaceAllString(str, ""), nil
3132
}
3233

3334
func FindMacroCommandEnd(str string, command string) (int, error) {
@@ -206,22 +207,3 @@ func FindEquations(str string) ([]string, error) {
206207

207208
return equations, nil
208209
}
209-
210-
func main() {
211-
data, err := ioutil.ReadFile("samples/tarball/GAN/adversarial.tex")
212-
if err != nil {
213-
log.Fatal(err)
214-
}
215-
216-
latex_source := string(data)
217-
latex_source = RemoveComment(latex_source)
218-
219-
equations, err := FindEquations(latex_source)
220-
if err != nil {
221-
log.Fatal(err)
222-
}
223-
224-
for _, s := range equations {
225-
fmt.Printf("%v\n", RemoveTags(s, []string{`\label`}))
226-
}
227-
}

0 commit comments

Comments
 (0)